Kotlin Program to Find Largest Among Three Numbers

In this post, we will go through Kotlin program to find largest among three numbers.

1. Find Largest Among Three Numbers (Integers) in Kotlin

Sourcecode –

import java.util.*

fun main() {

    val read = Scanner(System.`in`)

    println("Enter 1st Integer number:")
    val a = read.nextInt()

    println("Enter 2nd Integer number:")
    val b = read.nextInt()

    println("Enter 3rd Integer number:")
    val c = read.nextInt()

    var largestNum = if (a > b) a else b
    largestNum = if (largestNum > c) largestNum else c



    println("Largest Number is: $largestNum")
}

When you run the program, output will be

Enter 1st Integer number:
12
Enter 2nd Integer number:
43
Enter 3rd Integer number:
102
Largest Number is: 102
Explanation:

Methods/Functions used in this program –

  • nextInt(): Used to take Integer integer from standard input – Keyboard
  • println(): User to print output to console.

We have read integer from standard input ( i.e. Keyboard) using nextInt() and stored in variable a, b and c

Then, we defined another variable largestNum that stores largest number among the three integers.
At first, we compared between a and b. Whichever is greater among a and b, we stored it in largestNum.

Then, compared between value stored in largestNum and c. Whichever is greater, we stored it back in largestNum.

Finally, we print the result using println() function.

2. Find Largest Among Three Floating Point Numbers

Sourcecode –

import java.util.*

fun main() {

    val read = Scanner(System.`in`)

    println("Enter 1st Float number:")
    val a = read.nextFloat()

    println("Enter 2nd Float number:")
    val b = read.nextFloat()

    println("Enter 3rd Float number:")
    val c = read.nextFloat()

    var largestNum = if (a > b) a else b
    largestNum = if (largestNum > c) largestNum else c



    println("Largest Number is: $largestNum")
}

When you run the program, output will be

Enter 1st Float number:
12
Enter 2nd Float number:
23.4
Enter 3rd Float number:
54.9
Largest Number is: 54.9
Explanation:

Using this program, you can find largest number among three floating point numbers in Kotlin.

Methods/Functions used in this program –

  • nextFloat(): Used to take Float values from standard input – Keyboard
  • println(): User to print output to console.

We have read float from standard input ( i.e. Keyboard) using nextFloat() and stored in variable a, b and c

Then, we defined another variable largestNum that stores largest number among the three integers.
At first, we compared between a and b. Whichever is greater among a and b, we stored it in largestNum.

Then, compared between value stored in largestNum and c. Whichever is greater, we stored it back in largestNum.

Finally, we print the result using println() function.

Leave a Reply