Kotlin Program to Add two Numbers



In this article, we will understand how to add two numbers. This can be done using the ‘+’ operator. Below is a demonstration of the same

Suppose our input is

input1 : 10
input2 : 15

The desired output would be

Sum : 25

Algorithm

  • Step 1 − Start

  • Step 2 − Declare three integers: val1, val2 and sum

  • Step 3 − Define the integers

  • Step 4 − Add the two values using an addition operator (+)

  • Step 5 − Display the result

  • Step 6 − Stop

Example 1

In this example, we will add two numbers using the + operator. First, declare and set two integers i.e. number −

val val1 = 10
val val2 = 15

Now, calculate the sum using the Addition Arithmetic Operator −

val sum = val1 + val2

Let us now see the complete example −

fun main() { val val1 = 10 val val2 = 15 println("The two numbers are defined as " +val1 +" and " +val2) val sum = val1 + val2 println("The sum of the two integers is: " +sum) }

Output

The two numbers are defined as 10 and 15
The sum of the two integers is: 25

Example 2

Here, we have created a custom function

fun sum(val1 : Int, val2 : Int){ val sum = val1 + val2 println("The sum of the two integers is: " +sum) } fun main() { val val1 = 10 val val2 = 15 println("The two numbers are defined as " +val1 +" and " +val2) sum(val1, val2) }

Output

The two numbers are defined as 10 and 15
The sum of the two integers is: 25

Advertisements