Kotlin: Find the Largest of Three Numbers

1. Introduction

In this blog post, we will learn how to write a Kotlin Program to Find the Largest of Three Numbers.

2. Program Overview

Our Kotlin program will:

1. Prompt the user to input three distinct numbers.

2. Capture and store these numbers.

3. Determine and display which among the three is the largest.

3. Code Program

import java.util.Scanner

fun main() {
    // Engage the Scanner class for user input
    val reader = Scanner(System.in)

    // Request the user to furnish three numbers
    print("Enter the first number: ")
    val num1 = reader.nextDouble()
    print("Enter the second number: ")
    val num2 = reader.nextDouble()
    print("Enter the third number: ")
    val num3 = reader.nextDouble()

    // Determine the largest of the three numbers
    val largest = if (num1 >= num2 && num1 >= num3) {
        num1
    } else if (num2 >= num1 && num2 >= num3) {
        num2
    } else {
        num3
    }

    // Inform the user of the result
    println("The largest number among $num1, $num2, and $num3 is: $largest")
}

Output:

Enter the first number: 24.5
Enter the second number: 35.9
Enter the third number: 12.3
The largest number among 24.5, 35.9, and 12.3 is: 35.9

4. Step By Step Explanation

1. Scanner Activation: We first initiate the Scanner class from the java.util package, granting us the capability to collect user input. Our scanner object is aptly named reader.

2. Collecting Numbers: The user is then prompted, via the print function, to provide three numbers. Each of these numbers is stored in its respective variable: num1, num2, and num3.

3. Determining the Largest Number: The Kotlin if-else construct lets us compare the numbers. The logic flows as:

- If num1 is greater than or equal to both num2 and num3, then num1 is the largest.- If not, but num2 is greater than or matches both num1 and num3, then num2 reigns supreme.- Otherwise, num3 takes the crown.

4. Displaying the Result: Finally, the println function showcases the largest number to the user, wrapping up our numerical journey.

Comments