C++
#include <iostream>
using namespace std;
int main() {
int num;
cout << "Enter a number: ";
cin >> num;
if (num % 2 == 0) {
cout << num << " is even" << endl;
} else {
cout << num << " is odd" << endl;
}
return 0;
}Output
Enter a number: 7 7 is odd
Check Even or Odd in C++
This program determines whether a number is even or odd. This is one of the most fundamental programs in programming, teaching basic conditional logic, the modulo operator, and decision-making. Understanding even/odd is essential for many algorithms and problem-solving scenarios.
What are Even and Odd Numbers?
Even numbers:
- Divisible by 2 without remainder
- Examples: 0, 2, 4, 6, 8, 10, 12, ...
- When divided by 2, remainder is 0
Odd numbers:
- Not divisible by 2 (leave remainder 1)
- Examples: 1, 3, 5, 7, 9, 11, 13, ...
- When divided by 2, remainder is 1
Understanding the Modulo Operator (%)
The expression:
num % 2
means: "Divide num by 2 and give me the remainder."
Key properties:
- Even numbers always leave remainder ## 0 when divided by 2
- Odd numbers always leave remainder ## 1 when divided by 2
Examples:
10 % 2→ 0 (10 is even)13 % 2→ 1 (13 is odd)0 % 2→ 0 (zero is even)7 % 2→ 1 (7 is odd)
The if-else Condition
if (num % 2 == 0)
cout << num << " is even" << endl;
else
cout << num << " is odd" << endl;
How it works:
If condition is true (num % 2 == 0):
- Number is even
- Print: "num is even"
If condition is false (num % 2 != 0):
- Number is odd
- Print: "num is odd"
Summary
- Even numbers: divisible by 2 (remainder 0)
- Odd numbers: not divisible by 2 (remainder 1)
- Use modulo operator (
%) to check remainder num % 2 == 0means even, else odd- This is a fundamental pattern used in many programs
This program teaches:
- Modulo operator for remainder calculation
- Conditional statements (if-else)
- Decision-making in programming
- Basic input/output operations
Understanding even/odd checking is essential for:
- Many algorithmic problems
- Pattern recognition
- Array manipulation
- Mathematical programming