C++ Program to Check Odd or Even Number without using Modulo

C++ Program to Check Odd or Even Number without using Modulo

We all know about the odd and even numbers. In simple terms, if the number is divisible by two, it is even. If the number is not divisible by two, it is odd.

Explanation:

Finding odd/even numbers using the modulo operator is easy. Conventionally, we are using the modulo operator to check whether the number is even or odd. If (number%2==0) then the number is even else the number is odd.

But in competitive programming, this modulo operator can be very time-consuming. In this program, we are going to use the bitwise logical operation to check the odd and even numbers.

If we see odd numbers in binary form, their last bit is set(1). Whereas even numbers in binary form have the last bit not set(0).

Algorithm:

  • Perform logical “AND” operation between one and the number.
  • If the result is zero the number is even else the number is odd.

C++ Code:

#include <iostream>
using namespace std;
 
int main()
{
    int num = 13;

    if( num&1) cout<<"The number is odd.";
    
    else cout<<"The number is even.";

    return 0;
}

Output:

The number is odd.

You can try assigning other numbers to variable ‘num’.

Note: Odd number is different from odious number. Don’t get confused.

This is all about a C++ program to check odd or even number without using modulo. You can implement the same logic in any other programming languages like Java, Python, etc.

To improve your bit manipulation skills, check the set of bit manipulation questions in data structure coding questions.

Keep practicing!

Leave a Reply

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