w3resource

Kotlin program: Find maximum and minimum of three numbers


Write a Kotlin program to find the maximum and minimum of three numbers.


Pre-Knowledge (Before you start!)

  • Basic Kotlin Syntax.
  • Kotlin Functions.
  • Variables in Kotlin.
  • Built-in Functions.
  • String Interpolation.
  • Printing Output.

Hints (Try before looking at the solution!)

  • Define the main() Function.
  • Declare Three Numbers.
  • Display the Numbers.
  • Find Maximum and Minimum.
  • Display Results.
  • Test with Different Numbers.
  • Common Errors to Avoid:
    • Forgetting string interpolation.
    • Misplacing arguments in maxOf() or minOf().
    • Using mutable variables unnecessarily.

Sample Solution:

Kotlin Code:

fun main() {
    val number1 = 12
    val number2 = 10
    val number3 = 19
    
    println("Three numbers are: $number1,$number2,$number3")
    val maximum = maxOf(number1, number2, number3)
    val minimum = minOf(number1, number2, number3)
    println("Maximum of above three numbers: $maximum")
    println("Minimum of above three numbers: $minimum")
    
}

Sample Output:

Three numbers are: 12,10,19
Maximum of above three numbers: 19
Minimum of above three numbers: 10

Explanation:

In the above exercise -

  • Inside the "main()" function, three variables named number1, number2, and number3 are declared and assigned values of 12, 10, and 19, respectively.
  • The maxOf() function finds the maximum value among number1, number2, and number3. It takes multiple arguments and returns the maximum value.
  • The minOf() function finds the minimum value among number1, number2, and number3. It also takes multiple arguments and returns the minimum value.
  • The maximum value is stored in the maximum variable, and the minimum value is stored in the minimum variable.

Go to:


PREV : Check if a number is even or odd.
NEXT : Calculate the factorial of a given number.

Kotlin Editor:


Improve this sample solution and post your code through Disqus

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.