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


A number is even if it is divisible by two and odd if it is not divisible by two.

Some of the even numbers are −

2, 4, 6, 8, 10, 12, 14, 16

Some of the odd numbers are −

1, 3, 5, 7, 9, 11, 13, 15, 17

Check Whether Number is Even or Odd using Modulus

A program to check whether number is even or odd using modulus is as follows.

Example

 Live Demo

#include <iostream>
using namespace std;
int main() {
   int num = 25;
   if(num % 2 == 0)
   cout<<num<<" is even";
   else
   cout<<num<<" is odd";
   return 0;
}

Output

25 is odd

In the above program, the number num is divided by 2 and its remainder is observed. If the remainder is 0, then the number is even. If the remainder is 1, then the number is odd.

if(num % 2 == 0)
   cout<<num<<" is even";
else
   cout<<num<<" is odd";

Check Whether Number is Even or Odd Using Bitwise AND

A number is odd if it has 1 as its rightmost bit in bitwise representation. It is even if it has 0 as its rightmost bit in bitwise representation. This can be found by using bitwise AND on the number and 1. If the output obtained is 0, then the number is even and if the output obtained is 1, then the number is odd.

A program to check whether number is even or odd using Bitwise AND is as follows −

Example

 Live Demo

#include <iostream>
using namespace std;
int main() {
   int num = 7;
   if((num & 1) == 0)
   cout<<num<<" is even";
   else
   cout<<num<<" is odd";
   return 0;
}

Output

7 is odd

In the above program, bitwise AND is done on num and 1. If the output is 0, then num is even, otherwise num is odd.

if((num & 1) == 0)
cout<<num<<" is even";
else
cout<<num<<" is odd";

Samual Sam
Samual Sam

Learning faster. Every day.

Updated on: 24-Jun-2020

12K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements