Kotlin Program to Add Two Integers With Example

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.

Leave a Reply