In this tutorial, you shall learn how to find the largest of given three numbers in Kotlin, with the help of example programs.

Kotlin – Find largest of three numbers

To find the largest 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 greater than both b and c is

</>
Copy
a > b && a > c

If above condition is true, then a is the largest. If not, b or c is the largest.

To check the largest of b and c use the following condition.

</>
Copy
b > c

If above condition is true, then b is the largest. If not, c is the largest.

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 largest of these three numbers.

Main.kt

</>
Copy
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 largest of $a, $b, and $c")
    } else if (b > c) {
        print("$b is the largest of $a, $b, and $c")
    } else {
        print("$c is the largest of $a, $b, and $c")
    }
}

Output #1

Enter first number : 5
Enter second number : 1
Enter third number : 7
7.0 is the largest of 5.0, 1.0, and 7.0

Output #2

Enter first number : -9
Enter second number : 3
Enter third number : 0
3.0 is the largest of -9.0, 3.0, and 0.0

Related tutorials for the above program

Conclusion

In this Kotlin Tutorial, we learned how to find the largest of given three numbers.