w3resource

Scala control flow program: Find the maximum of two numbers

Scala Control Flow Exercise-2 with Solution

Write a Scala program to find the maximum of two given numbers using if/else statements.

Sample Solution:

Scala Code:

object MaximumFinder {
  def main(args: Array[String]): Unit = {
    val n1: Int = 20 // First number
    val n2: Int = 15 // Second number

    var max: Int = 0 // Initialize the maximum variable

    if (n1 > n2) {
      max = n1
    } else {
      max = n2
    }

    println(s"The maximum of $n1 and $n2 is: $max")
  }
}

Sample Output:

The maximum of 20 and 15 is: 20

Explanation:

First we define two variables n1 and n2 and provide them values (20 and 15 in this case) to compare. We initialize a variable max to store the maximum value. Using the if/else statements, we compare n1 and n2. If n1 is greater than n2, we assign n1 to the max. Otherwise, we assign n2 to max. Finally, we print the result using println, which displays the maximum value along with the original numbers.

Scala Code Editor :

Previous: Check the number positive, negative, or zero.
Next: Scala control flow program to check even or odd number.

What is the difficulty level of this exercise?



Follow us on Facebook and Twitter for latest update.