🔍 Check Even or Odd Using Bitwise AND in C++

Check Even or Odd Using Bitwise AND in C++

🔍 Check Even or Odd Using Bitwise AND in C++

Checking whether a number is even or odd is a common task in programming. While the modulus operator (%) is frequently used, a more efficient and faster method uses the bitwise AND operator (&). This operator works directly on the binary representation of numbers.

💡 How Bitwise AND Helps in Even/Odd Check

In binary, even numbers always end with a 0 bit, and odd numbers end with a 1 bit. The bitwise AND operator can isolate the least significant bit (LSB) by performing number & 1.

  • If number & 1 == 0, the number is even.
  • If number & 1 == 1, the number is odd.

📄 C++ Code Example


#include <iostream>
using namespace std;

int main() {
    int number;

    // Input from user
    cout << "Enter an integer: ";
    cin >> number;

    // Check even or odd using bitwise AND
    if ((number & 1) == 0) {
        cout << number << " is even." << endl;
    } else {
        cout << number << " is odd." << endl;
    }

    return 0;
}
    

✅ Sample Output

Enter an integer: 8
8 is even.

Enter an integer: 15
15 is odd.
  

📘 Definition: Even or Odd Check Using Bitwise AND

Checking even or odd using the bitwise AND operator involves inspecting the least significant bit of a number’s binary representation. By performing number & 1, the result isolates this bit. If the result is 0, the number is even; if 1, the number is odd.

This method is faster than using modulus because bitwise operations directly manipulate bits without performing division. It is widely used in performance-critical applications and low-level programming.

🧠 Final Thoughts

Using bitwise AND to check for even or odd numbers is an elegant and efficient approach. Understanding this technique enhances your knowledge of bitwise operations and improves your problem-solving skills.

Post a Comment

Post a Comment (0)

Previous Post Next Post

ads

ads

Update cookies preferences