Check if a given Number is Even or Odd

By | November 27, 2024

Given a positive integer N, the task is to check whether the given number N is Even or Odd.

Examples:

Input : N = 10
Output : Even

Input : N = 5
Output : Odd

Method 1:
An even number is an integer which is “evenly divisible” by 2. This means that if the integer is divided by 2, it yields no remainder or 0 as remainder. Similarly, an Odd number is an integer which is not “evenly divisible” by 2 and will leaves 1 as remainder.

Below is the implementation of above approach:

// Scala program to check
// whether the given number
// is Even or Odd

// Creating Object
object W3Colleges {

  // Function to check  
  // whether the given number
  // is Even or Odd
  def isEvenOrOdd(N: Int): String = { 
    if (N % 2 == 0)
      "Even"
    else
      "Odd"
  } 

  // Driver Code 
  def main(args: Array[String]): Unit = { 
    val N = 10

    println(s"The number $N is ${isEvenOrOdd(N)}.") 
  } 
}

Output:

Even

Method 2: Using Bit Manipulation
This method is based on the fact that a number is Odd if Bit-wise AND (&) of the number with 1 is 1 and Even if 0.

Below is the implementation of above approach:

// Scala program to check
// whether the given number
// is Even or Odd

// Creating Object
object W3Colleges {

  // Function to check 
  // whether the given number
  // is Even or Odd through 
  // Bitwise AND operation
  def isEvenOrOdd(N: Int): String = { 
    if ((N & 1) == 1)
      "Odd"
    else
      "Even"
  } 

  // Driver Code 
  def main(args: Array[String]): Unit = { 
    val N = 10

    println(s"The number $N is ${isEvenOrOdd(N)}.") 
  } 
}

Output:

Even
Author: Mithlesh Upadhyay

Mithlesh Upadhyay is a Computer Science and AI expert from Madhya Pradesh with strong academic background (BE in CSE and M.Tech in AI) and over six years of experience in technical content development. He has contributed tech articles, led teams, and worked in Full Stack Development and Data Science. He founded the w3colleges.org portal for learning resources.