C++ Program to Check Even/Odd Using Bitwise AND with Explanation
C++
Medium
Operators
29 views
1 min read
148 words
This problem helps you practice core C++ fundamentals in a practical way. It builds intuition around odd, even, check. Let’s break it down step by step so you can implement it confidently.
Problem Statement
Use bitwise AND with 1 to check even/odd instantly.
Real Life: Fastest way to check even/odd in programming.
Input Format
An integer N.
Output Format
Print
• Even
OR
• Odd
Constraints
• Integer value
• Works for positive and negative numbers
Concept Explanation
The least significant bit (LSB) decides even or odd:
• If LSB is 0 → Even
• If LSB is 1 → Odd
Bitwise AND with 1 checks this instantly.
Step-by-Step Logic
1.Take input number N.
2.Apply bitwise AND: N & 1.
3.If result is 0:
• Print Even.
4.Else:
• Print Odd.
Code Solution
This explanation is written for learning purposes and to help beginners understand the concept clearly.
void operator_q9_even_odd_bitwise() {
int numbers[] = {12, 15, 18, 21, 24};
for(int i = 0; i < 5; i++) {
if(numbers[i] & 1) {
cout << numbers[i] << " is Odd" << endl;
} else {
cout << numbers[i] << " is Even" << endl;
}
}
}
Common Mistakes
- Misreading input/output format.
- Not handling constraints and edge cases.
- Off-by-one errors in loops.
- Forgetting to reset variables between test cases (if any).
Solution Guide
Problem
Use bitwise AND with 1 to check even/odd instantly.
Real Life: Fastest way to check even/odd in programming.
Input / Output
Output
Print
• Even
OR
• Odd
Constraints
• Integer value
• Works for positive and negative numbers
Explanation
Concept Explanation
The least significant bit (LSB) decides even or odd:
• If LSB is 0 → Even
• If LSB is 1 → Odd
Bitwise AND with 1 checks this instantly.
Step-by-Step Explanation
1.Take input number N.
2.Apply bitwise AND: N & 1.
3.If result is 0:
• Print Even.
4.Else:
• Print Odd.
Details
Common Mistakes
- Misreading input/output format.
- Not handling constraints and edge cases.
- Off-by-one errors in loops.
- Forgetting to reset variables between test cases (if any).
Official Solution
void operator_q9_even_odd_bitwise() {
int numbers[] = {12, 15, 18, 21, 24};
for(int i = 0; i < 5; i++) {
if(numbers[i] & 1) {
cout << numbers[i] << " is Odd" << endl;
} else {
cout << numbers[i] << " is Even" << endl;
}
}
}
Solutions (0)
No solutions submitted yet. Be the first!