Kotlin Program to add two numbers

20 = 10 + 10

35 = 15 + 20


Example 1: How to add two numbers in Kotlin.

import java.util.Scanner

fun main(args: Array<String>) {

    var a: Int
    var b: Int
    var sum: Int

    var sc = Scanner(System.`in`)

    print("Enter two numbers:")
    a = sc.nextInt()
    b = sc.nextInt()

    sum = a + b

    println("Sum is:$sum")


Enter two numbers:10 20

Sum is:30

Example 2: Kotlin Program to Add Two Integers

fun main(args: Array<String>) {

    val first: Int = 10
    val second: Int = 20

    val sum = first + second

    println("The sum is: $sum")

When you run the program, the output will be:

The sum is: 30

In this program, similar to Java, two integers 10 and 20 are stored in integer variables first and second respectively. It is not mandatory to add :Int in the variable declaration, Kotlin automatically assigns a type (in this case Int).

Then, first and second are added using the + operator, and its result is stored in another variable sum.

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

I hope you found what you were looking for from this tutorial. If you want more Kotlin tutorials like this, then do join our Telegram channel for future updates.

Thanks for reading, have a nice day 🙂

Leave a Comment

Your email address will not be published.