Coronavirus Outbreak - 2020, 100+ dead in China, effected several countries, Checkout WHO Advices to stay safe

Kotlin Program to Add Two Integers With Example

Greetings!
We have recently published 100+ articles on android tutorials with kotlin and java. If you need, you may visit Android Tutorial for beginners page. You can also check Kotlin Tutorial for beginners. Also, if you are interested in content writing, you can mail us at tutorialwing@gmail.com.

In this post, we will go through kotlin program to add two integers with or without user input. After addition, result will be displayed on the screen.

1. Example: Add Two Integers in Kotlin Without User Input

fun main(args: Array<String>) {

    val firstNum = 100
    val secondNum = 200

    val sum = firstNum + secondNum

    println("sum = $sum")
}

When you run the program, output will be:

sum = 300

Explanation

We have defined two variables firstNum and secondNum to store two integer values.

At first, defined firstNum and assigned value 100 to it.
Then, defined defined secondNum and assigned value 200 to it.

Then, we defined another variable sum that stores sum of 2 variables (firstNum and secondNum).

Finally, value of sum is printed on the screen using println() function.

What if you want to take input from user and then add it?

2. Example: Add Two Integers in Kotlin With User Input

import java.util.*

fun main(args: Array<String>) {

    val read = Scanner(System.`in`)

    println("Enter first integer number:")
    val firstNum = read.nextInt()

    println("Enter second integer number:")
    val secondNum = read.nextInt()

    val sum = firstNum + secondNum

    println("sum = $sum")
}

When you run the program, output will be:

Enter first integer number:
100
Enter second integer number:
200
sum = 300

Explanation

Here, we have created an object of Scanner to take input from user.

We are reading the entered value using read.nextInt()

At first, we are storing the entered value in firstName using read.nextInt().

Then, we are storing the entered value in secondNum using using read.nextInt().

Then, addition is calculated and stored in sum.

Finally, sum is being displayed using println() function.

Thus,
We went through kotlin program to add two integers with or without user input.

Support Us

If you like Tutorialwing and would like to contribute, you can email an article on any educational topic at tutorialwing@gmail.com. We would love to publish your article. See your article on Tutorialwing and help others with your knowledge. Follow Facebook, LinkedIn, Google+, Twitter, Youtube for latest updates.
Greetings!
We have recently published 100+ articles on android tutorials with kotlin and java. If you need, you may visit Android Tutorial for beginners page. You can also check Kotlin Tutorial for beginners

Leave a Reply