Kotlin – Find minimum of two numbers

Find Minimum of Two Numbers in Kotlin

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

Finding the minimum of two numbers is a common task in programming. In Kotlin, you can achieve this by using a simple comparison between the given two numbers, and using this comparison expression as a condition in the if-else construct.

To compare the given two numbers, we can use Less-than comparison operator.

Example

Finding Minimum of Two Numbers

We’ll start with an example of finding the minimum of two numbers.

In this example, the findMinimum() function compares two numbers and returns the smallest of the two.

Kotlin Program

// Function to find minimum of two numbers
fun findMinimum(a: Int, b: Int): Int {
    if (a < b) {
        return a
    } else {
        return b
    }
}

fun main() {
    val number1 = 8
    val number2 = 12
    val minimum = findMinimum(number1, number2)
    println("Minimum of $number1 and $number2 is: $minimum")
}

Output

Minimum of 8 and 12 is: 12

Summary

In this Kotlin Tutorial, we learned how to find the minimum of given two numbers in Kotlin, using less than comparison operator, with the help of example programs.