In this tutorial, you shall learn how to find the smallest of given three numbers in Kotlin, with the help of example programs.
Kotlin – Find smallest of three numbers
To find the smallest of given three numbers in Kotlin, we can use comparison operators and conditional statements.
If a
, b
, and c
are given three numbers, the condition to check if a
is less than both b
and c
is
a < b && a < c
If above condition is true, then a
is the smallest. If not, b
or c
is the smallest.
To check the smallest of b
and c
use the following condition.
b < c
If above condition is true, then b
is the smallest. If not, c
is the smallest.
Program
In the following program, we read three numbers from user and store them in a
, b
, and c
. We then use the above explanation to write logic for finding the smallest of these three numbers.
Main.kt
fun main() { print("Enter first number : ") val a = readLine()!!.toDouble() print("Enter second number : ") val b = readLine()!!.toDouble() print("Enter third number : ") val c = readLine()!!.toDouble() if (a < b && a < c) { print("$a is the smallest of $a, $b, and $c") } else if (b < c) { print("$b is the smallest of $a, $b, and $c") } else { print("$c is the smallest of $a, $b, and $c") } }
Output #1
Enter first number : 8 Enter second number : 1 Enter third number : 7 1.0 is the smallest of 8.0, 1.0, and 7.0
Output #2
Enter first number : -9 Enter second number : 41 Enter third number : 120 -9.0 is the smallest of -9.0, 41.0, and 120.0
Related tutorials for the above program
Conclusion
In this Kotlin Tutorial, we learned how to find the smallest of given three numbers.