Here is a C++ program to check whether a number is odd or even using bitwise operator. Even Numbers are integers which is divisible by 2 whereas numbers which are not divisible by 2 are odd numbers.
Even Numbers examples: 2, 4, 6, 10 ...
Odd Number examples: 1, 7, 9 ,11 ...
C++ Program to check whether a number is Odd or Even number using modulus operator
We can use modulus operator for checking whether a number is odd or even, if after dividing a number by 2 we get 0 as remainder(number%2 == 0) then it is even number otherwise it is odd number.
#include <iostream> using namespace std; int main() { int num; cout << "Enter an Integer\n"; cin >> num; if (num % 2 == 0) { cout << num << " is EVEN Number"; } else { cout << num << " is ODD Number"; } return 0; }Output
Enter an Integer 13 13 is ODD Number
Enter an Integer 8 8 is EVEN Number
C++ Program to check Odd or Even Numbers using bitwise operators
If the least significant bit of number is 0, then number is even otherwise number is odd. We can check least significant bit of any number by doing bitwise and with 1.
#include <iostream> using namespace std; int main() { int num; cout << "Enter an Integer\n"; cin >> num; // if Least significant bit of number is 0, // Then it is even otherwise odd number if (num & 1 == 0) { cout << num << " is EVEN Number"; } else { cout << num << " is ODD Number"; } return 0; }Output
Enter an Integer 15 15 is ODD Number
Enter an Integer 4 4 is EVEN Number
Recommended Posts