Check whether a number is odd or even using a bitwise operator in C++

In this tutorial, we will learn how to check whether a number is odd or even using a bitwise operator in C++.  Normally, we check if the number is divisible by 2 and based on that we conclude if it is even or odd. In this tutorial, we will do the same but using a bitwise operator in our program.

As we know that in the binary representation of a number the least significant bit is 1 if the number is odd otherwise it’s 0. Consider numbers 7,8,9, and 10. Binary forms of these numbers are 0000 0111, 0000 1000, 0000 1001, and 0000 1010 respectively. As you can notice 8 and 10 are even numbers hence ending with a zero in their binary form. Similarly, 7 and 9 are odd numbers and hence ending with a 1 in their binary form.

We can use this property to distinguish between odd and even numbers. Let’s say we have 7. The binary form of 7 is 0000 0111. Now if we do bitwise AND operation on this number with 0000 0001 then we get 0000 0001 which equals 1(true). In the same way, take any odd number and do the above operation, you will get the output as 1. But if the number is even, then bitwise AND operation will produce the result as 0000 0000 which equals zero(false).

For example,
if the number is 8. Its binary representation is 0000 1000. When we do AND operation on this number with 1, we get the following.

0000 1000

&

0000 0001
___________

0000 0000 = 0(false)
___________

Therefore, we can say that,

if (n & 1)
{
    //odd number
}
else
{
    //even number
}

Here n is the given number as input.

See the given example program to understand the concept.

#include <iostream>
using namespace std;

int main()
{
  int n;
  cout << "Enter a number.\n";
  cin >> n;
  if (n & 1)
  {
    cout << "Number is ODD.\n";
  }
  else
  {
    cout << "Number is EVEN\n";
  }
  
  return 0;
}

The output is:

Enter a number.
7
Number is ODD.

Thank you.

Also, read: C++ program to separate even and odd numbers from an array

Leave a Reply

Your email address will not be published. Required fields are marked *