Given a number, check whether it is "Odd" or "Even"
The modulo operator %
returns the remainder of a division.
Examples:
10 % 2 = 0
(10 รท 2 = 5 remainder 0)11 % 2 = 1
(11 รท 2 = 5 remainder 1)15 % 4 = 3
(15 รท 4 = 3 remainder 3)For odd/even checking:
num % 2 == 0
โ Number is EVENnum % 2 == 1
(or != 0) โ Number is ODDโ
Works for negative numbers too! -10 % 2 = 0
(even)
Key Rule: When there's only ONE statement after if
or else
, you can omit the braces { }
.
With braces (traditional):
if (condition) { statement; } else { statement; }
Without braces (compact):
if (condition) statement; else statement;
Our code example:
if (a % 2 == 0)
cout << "EVEN";
else
cout << "ODD";
โ This works because each block has exactly one statement.
โ ๏ธ Warning: If you need multiple statements, you MUST use braces!
if (condition) {
statement1;
statement2;
}
โ Common mistake without braces:
if (condition)
statement1;
statement2; // This will ALWAYS execute!
๐ก Best Practice: Use braces for readability, especially when you're learning. Omitting them is convenient but can lead to bugs if you add more statements later.
Step-by-step execution:
if (a % 2 == 0)
a % 2
(remainder when divided by 2)cout << "EVEN";
else
and execute cout << "ODD";
Example with a = 10:
10 % 2 = 0
0 == 0
is TRUEExample with a = 2461:
2461 % 2 = 1
1 == 0
is FALSEโ Safe to omit braces:
๐ก๏ธ Always use braces when:
๐ก Pro tip: Many coding style guides (like Google's C++ Style Guide) recommend always using braces to prevent bugs, even for single statements.
๐ก Tip: The modulo operator is your best friend for checking divisibility and finding remainders!
#include <iostream>
using namespace std;
int main() {
long long a;
cin >> a;
if (a % 2 == 0)
cout << "EVEN";
else
cout << "ODD";
return 0;
}