2. Check Odd or Even

Easy โฑ๏ธ 5 min

Problem Statement

Given a number, check whether it is "Odd" or "Even"

Input Format:
Accept an Integer as input
Output Format:
Print the output as "Odd" or "Even"
Constraints:
1 <= INPUT <= 10^15
Sample Input 1:
-10
Sample Output 1:
EVEN
Sample Input 2:
2461
Sample Output 2:
ODD
๐Ÿงฑ C++ Conditionals & Modulo Operator Guide
โž— The Modulo Operator (%) โ–ผ

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:

  • If num % 2 == 0 โ†’ Number is EVEN
  • If num % 2 == 1 (or != 0) โ†’ Number is ODD

โœ… Works for negative numbers too! -10 % 2 = 0 (even)

๐Ÿšซ If-Else WITHOUT Curly Braces { } โ–ผ

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.

๐Ÿ“ How the Code Works โ–ผ

Step-by-step execution:

if (a % 2 == 0)

  • Calculate a % 2 (remainder when divided by 2)
  • Check if remainder equals 0
  • If TRUE โ†’ Execute cout << "EVEN";
  • If FALSE โ†’ Skip to else and execute cout << "ODD";

Example with a = 10:

  • 10 % 2 = 0
  • 0 == 0 is TRUE
  • Output: "EVEN"

Example with a = 2461:

  • 2461 % 2 = 1
  • 1 == 0 is FALSE
  • Go to else block
  • Output: "ODD"
๐ŸŽฏ When to Use Braces vs Without โ–ผ

โœ… Safe to omit braces:

  • Only ONE statement in the if/else block
  • Code is very short and simple
  • You're confident you won't add more statements

๐Ÿ›ก๏ธ Always use braces when:

  • You have multiple statements
  • Working in a team (readability matters)
  • Code might be modified later
  • Using nested if-else statements

๐Ÿ’ก 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!

Solution

#include <iostream>

using namespace std;

int main() {
    long long a;
    cin >> a;
    
    if (a % 2 == 0)
        cout << "EVEN";
    else
        cout << "ODD";
    
    return 0;
}