w3resource

Scala control flow program to check even or odd number

Scala Control Flow Exercise-3 with Solution

Write a Scala program to check if a given number is even or odd using if/else statements.

Sample Solution:

Scala Code:

object EvenOddChecker {
  def main(args: Array[String]): Unit = {
    //val number: Int = 15 // Number you want to check
      val number: Int = 20 // Number you want to check

    if (number % 2 == 0) {
      println(s"The number $number is even.")
    } else {
      println(s"The number $number is odd.")
    }
  }
}

Sample Output:

The number 15 is odd.
 
The number 20 is even.

Explanation:

First we define a variable "number" and assign it a value to check. We use the modulo operator % to check if the remainder of "number" divided by 2 is equal to 0. If the remainder is 0, it means the number is divisible by 2 and hence even. In that case, we print "The number is even." If the remainder is not 0, it means the number is not divisible by 2 and hence odd. In that case, we print "The number is odd."

Scala Code Editor :

Previous: Find the maximum of two numbers.
Next: Find a factorial with a while loop.

What is the difficulty level of this exercise?



Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://w3resource.com/scala-exercises/control-flow/scala-control-flow-exercise-3.php