Kotlin – Find the Largest of three numbers

Find Largest of Three Numbers in Kotlin

In this tutorial, you’ll learn how to find the largest of three numbers using Kotlin.

Finding the largest of three numbers can be done using comparison operators and if else statement.

To find the largest of the given three numbers, follow these steps.

  1. Start. Given three numbers.
  2. Check if first number is greater than both the second and the third number. If it is, then the first number is the largest. Go to end.
  3. If the first number is not greater than both of the other numbers, then check if the second number is greater than the second number. If it is, then the second number is the largest. Go to end
  4. If the second number is not greater than third number, then third number must be the largest.
  5. End of finding the largest of three numbers.

Example

Finding Largest of Three Numbers

We’ll start with an example of finding the largest of give three numbers.

In this example, the findLargest() function compares the given three numbers and returns the largest.

Kotlin Program

// Function to find largest of three numbers
fun findLargest(a: Int, b: Int, c:Int): Int {
    if (a > b && a > c) {
        return a
    } else if (b > c) {
        return b
    } else {
        return c
    }
}

fun main() {
    val number1 = 8
    val number2 = 12
    val number3 = 7
    val largest = findLargest(number1, number2, number3)
    println("Largest of $number1, $number2, and $number3 is: $largest")
}

Output

Largest of 8, 12, and 7 is: 12

Summary

In this Kotlin Tutorial, we learned how to find the largest of given three numbers in Kotlin, using comparison operators and if-else-if statement, with the help of example programs.