w3resource

Scala control flow program: Find the maximum of two numbers


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


Pre-Knowledge (Before You Start!)

Before attempting this exercise, ensure you have a good understanding of the following concepts:

  • Conditional Statements: Understand how if and else statements work in Scala.
  • Comparison Operators: Learn how to compare two numbers using > and <.
  • Variable Declaration: Understand how to declare and assign values to variables in Scala.
  • Printing Output: Learn how to use println() to display results in the console.

Hints (Try Before Looking at the Solution!)

Consider the following hints to help you solve this exercise:

  • Hint 1: Store two numbers in variables before performing any comparisons.
  • Hint 2: Use an if condition to check which number is greater.
  • Hint 3: Store the greater number in a variable to use later.
  • Hint 4: Print the maximum number along with the original values.

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.