Kotlin Program – Average of Two Numbers

Kotlin – Average of two numbers

In Kotlin, you can find the average of given two numbers by first finding their using Arithmetic Addition operator `+`, and the dividing the sum by 2 using Arithmetic Division operator.

The two arguments can be of any numeric data type.

For example, if `a` and `b` are the two given numbers, then the expression to find their average is

``(a + b) / 2``

Examples

Average of the two numbers 10 and 20

In the following example, we take two number values in `a` and `b`, and find their average using the above specified expression.

Kotlin Program

``````fun main() {
val a = 10
val b = 20
val average = (a + b) / 2
println("Average : \$average")
}``````

Output

``Average : 15``

Explanation

``````Average = (10 + 20) / 2
= (30) / 2
= 15``````

Average of the two numbers 3.14 and 1.20

In the following example, we take two floating point numbers in `a` and `b`, and find their average.

Kotlin Program

``````fun main() {
val a = 3.14
val b = 1.20
val average = (a + b) / 2
println("Average : \$average")
}``````

Output

``Average : 2.17``

Explanation

``````Average = (3.14 + 1.2) / 2
= (4.34) / 2
= 2.14``````