w3resource

Scala function: Check if a number is even


Write a Scala function to check if a given number is even.


Before you start!

To solve this problem, you should have a basic understanding of:

  • Scala functions and how to define them.
  • Integer division and modulus operations.
  • The mathematical property of even numbers (a number is even if it is divisible by 2).
  • Boolean expressions and return values in Scala.

Try before looking at the solution!

Think about how you can check if a number is even:

  • Which mathematical operator helps determine if a number is even?
  • How does the modulus operator (%) work in Scala?
  • What should the function return for even and odd numbers?
  • Can you optimize your function using a single-line return statement?

Sample Solution:

Scala Code:

object NumberChecker {
  def isEven(number: Int): Boolean = {
    number % 2 == 0
  }

  def main(args: Array[String]): Unit = {
    val number1 = 8
    val number2 = 11

    println(s"Is $number1 is even? ${isEven(number1)}")
    println(s"Is $number2 is even? ${isEven(number2)}")
  }
}

Sample Output:

Is 8 is even? true
Is 11 is even? false

Scala Code Editor :

Previous: Calculate the Power of a Number.
Next: Check if a number is a perfect square.

What is the difficulty level of this exercise?



Follow us on Facebook and Twitter for latest update.