In this tutorial, you shall learn how to write a program to find the average of given two numbers in Kotlin.

Kotlin – Average of Two Numbers

To find the average of two numbers in Kotlin, compute the sum of two numbers and divide the sum by 2. The resulting value of the division operation is the average of given two numbers.

For example if a and b are given numbers, then the average of these two numbers can be found out by the following expression.

(a + b) / 2

Program

In the following program, we take read two numbers from user and store then in a and b, and then find their average using the above formula.

Main.kt

fun main() {
    print("Enter first number : ")
    val a = readLine()!!.toDouble()

    print("Enter second number : ")
    val b = readLine()!!.toDouble()

    val avg = (a + b) / 2
    println("Average of $a and $b is $avg.")
}

Output #1

Enter first number : 4
Enter second number : 1
Average of 4.0 and 1.0 is 2.5.

Output #2

Enter first number : 24
Enter second number : 87
Average of 24.0 and 87.0 is 55.5.
ADVERTISEMENT

Related Tutorials

Conclusion

In this Kotlin Tutorial, we learned how to find the average of two numbers using Addition and Division operators.