C++ Program to Check Whether the Given Number is Even or Odd

This C++ program to check whether the given number is even or odd.

even numbers are perfectly divisible by 2. In this example program, if else statement is used to check whether a number entered by the user is even or odd.

#include <iostream>
using namespace std;

int main() {
  int a;
  cout << "Enter the number: "; cin >> a;
  /* logic */
  if (a % 2 == 0) {
    cout << "The given number is EVEN" << endl;
  } else {
    cout << "The given number is ODD" << endl;
  }

  return 0;
}
Program Output:
Enter the number: 8

The given number is EVEN
Explanation:

Example 1: If entered number is an even number.

Let value of 'a' entered is 8

if(a%2==0) then a is an even number, else odd.

i.e. if(8%2==0) then 8 is an even number, else odd.

To check whether 8 is even or odd, we need to calculate (8%2).

/* % (modulus) implies remainder value. */

/* Therefore if the remainder obtained when 8 is divided by 2 is 0, then 8 is even. */

8%2==0 is true

Thus 8 is an even number.

Example 2: If entered number is an odd number.

Let value of 'a' entered is 7

if(a%2==0) then a is an even number, else odd.

i.e. if(7%2==0) then 4 is an even number, else odd.

To check whether 7 is even or odd, we need to calculate (7%2).

7%2==0 is false /* 7%2==1 condition fails and else part is executed */

Thus 7 is an odd number.


Scroll Back to Top