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

Kotlin – Find largest of two numbers

To find the largest of given two numbers in Kotlin, we can use Greater-than or Less-than operator and compare the two numbers.

If a and b are given two numbers, the condition to check if a is greater than b is

a > b

The above condition returns true if a is greater than b, or else, it returns false.

Program

In the following program, we read two numbers from user and store them in a and b, then use Greater-than comparison operator to find the largest of a and b.

Main.kt

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

    if (a > b) {
        print("$a is the largest of $a and $b")
    } else {
        print("$b is the largest of $a and $b")
    }
}

Output #1

Enter first number : 4
Enter second number : 6
6.0 is the largest of 4.0 and 6.0

Output #2

Enter first number : -9
Enter second number : 7
7.0 is the largest of -9.0 and 7.0

Related tutorials for the above program

ADVERTISEMENT

Conclusion

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