A number is classified as even or odd based on whether it is completely divisible by 2.
- If a number leaves a remainder of 0 when divided by 2, it is an even number.
- If it leaves a non-zero remainder, it is an odd number.
Example:
Input: N = 4
Output: Even
Explanation: 4 is divisible by 2 with no remainder, so it is an even number.Input: N = 7
Output: Odd
Explanation: 7 is not completely divisible by 2 leaving 1 as remainder, so it is an odd number.
Methods to check Odd or Even Number
There are three different methods which we can use to check if the given number is an odd number or an even number:
1. Check Odd or Even Number Using Modulo Operator
The modulo operator % returns the remainder when one number is divided by another. It can be used to determine whether a number is divisible by 2.
- If number % 2 == 0, the number is even.
- Otherwise, the number is odd.
#include <stdio.h>
void checkOddEven(int N) {
// Find the remainder
int r = N % 2;
// Condition for even
if (r == 0) {
printf("Even");
}
// Condition for odd number
else {
printf("Odd");
}
}
int main() {
int N = 101;
checkOddEven(N);
return 0;
}
Output
Odd
2. Check Odd or Even Number Using Bitwise AND Operator
The least significant bit (LSB) of a number's binary representation indicates whether the number is odd or even.
- For an odd number, the LSB is 1, while for an even number, the LSB is 0.
- The bitwise AND operator & can be used with 1 to check the LSB and determine whether the number is odd or even.
Approach:
- Use the bitwise AND operator on the given number with mask = 1 to extract the LSB of the number.
- If the result is 0, the given number is even.
- If the result is 1, the given number is odd.
#include <stdio.h>
void checkEvenOdd(int N) {
// Check if the number is even or odd using bitwise
// AND operator
if (N & 1) {
printf("Odd\n");
}
else {
printf("Even\n");
}
}
int main() {
int N = 7;
checkEvenOdd(N);
return 0;
}
Output
Odd
3. Check Odd or Even Number Using Shift Operator
The least significant bit (LSB) is 1 for odd numbers and 0 for even numbers. We can use right and left shift operations to remove and restore the LSB and compare the result with the original number.
- Right shift the number by one bit and then left shift it by one bit to clear the LSB.
- If the result differs from the original number, it is odd; otherwise, it is even.
#include <stdio.h>
void checkEvenOdd(int num) {
int temp = num;
temp = temp >> 1;
temp = temp << 1;
// Check if the number is even or odd using bitwise AND operator
if (temp == num) {
printf("Even\n");
}
else {
printf("Odd\n");
}
}
int main() {
int num = 7;
checkEvenOdd(num);
return 0;
}
Output
Odd