In C++, a number can be classified as even or odd by checking its divisibility by 2 or examining its binary representation. Different operators can be used to perform this check, with the modulo operator being the simplest approach.
- The modulo operator checks the remainder after division by 2.
- Bitwise operators can determine the result by examining the least significant bit.
Examples
Input: n = 11
Output: Odd
Explanation: Since 11 is not completely divisible by 2, it is an odd number.Input: n = 20
Output: Even
Explanation: Since 20 is completely divisible by 2, it is an even number.
Methods to Check Whether a Number is Even or Odd
A number can be checked for even or odd using the modulo operator, bitwise AND operator, or bitwise shift operations.
Method 1: Using Modulo Operator (%)
The modulo operator (%) returns the remainder after dividing one number by another. When a number is divided by 2, a remainder of 0 indicates an even number.
- If n % 2 == 0, the number is even.
- Otherwise, the number is odd.
#include <bits/stdc++.h>
using namespace std;
int main() {
int n = 11;
// If n is completely divisible by 2
if (n % 2 == 0)
cout << "Even";
// If n is NOT completely divisible by 2
else
cout << "Odd";
return 0;
}
Output
Odd
Method 2: Using Bitwise AND (&) Operator
The bitwise AND operator (&) can be used to check the least significant bit (LSB) of an integer. In the binary representation of an integer, an even number has an LSB of 0, while an odd number has an LSB of 1.
- n & 1 extracts the least significant bit of n.
- If the result is 0, the number is even.
- If the result is 1, the number is odd.
#include <bits/stdc++.h>
using namespace std;
int main() {
int n = 11;
// Performing AND operation of n with 1
int res = n & 1;
// If res is 0, the number is even
if (res == 0)
cout << "Even";
// Otherwise, number is odd
else
cout << "Odd";
return 0;
}
Output
Odd
Method 3: Using Bitwise Shift Operators (<< and >>)
A number can also be checked using right and left shift operations. Right shifting an integer by one position removes its least significant bit, and shifting it back left restores the remaining bits while setting the LSB to 0.
- Store the original number in a temporary variable.
- Right shift the temporary value by one position.
- Left shift it by one position to restore the remaining bits.
- If the resulting value is equal to the original number, the number is even; otherwise, it is odd.
#include <iostream>
using namespace std;
int main() {
int n = 11;
// Variable to store the original number
int temp = n;
// Right shift the number by 1
temp = temp >> 1;
// Left shift the number back by 1
temp = temp << 1;
// Check if the value of the number changed
// or not
if (temp == n) {
cout << "Even" << endl;
} else {
cout << "Odd" << endl;
}
return 0;
}
Output
Odd