Learning C++ from Scratch: Practical Cases of if-else Conditional Statements

1. What is the if-else Conditional Statement?

In programming, we often need to perform different operations based on various conditions. For example, determining if an exam score is passing and outputting “Pass” or “Fail”, or checking if it’s raining and deciding whether to remind someone to bring an umbrella. In such cases, we use conditional statements, with the most basic being the if-else statement.

The core idea of if-else is: If a condition is true, execute a block of code; otherwise, execute another block of code. This gives programs “decision-making ability,” moving beyond simple sequential execution.

2. Basic Syntax of if-else

In C++, the syntax of if-else has several common forms:

2.1 Single Condition Check (if)

if (condition_expression) {
    // Code to execute when condition_expression is true
}
  • Condition Expression: Must return a boolean value (true or false), e.g., score >= 60 (whether the score is passing).
  • Code Block: A segment of code enclosed in curly braces {}. Executed when the condition is true. While braces can be omitted for a single statement, it is recommended to always use braces to avoid logical errors.

2.2 Two-Choice Check (if-else)

if (condition_expression) {
    // Executed when condition_expression is true
} else {
    // Executed when condition_expression is false
}
  • If the condition is true, execute the code in the if block; otherwise, execute the else block.

2.3 Multi-Condition Check (else if)

For multiple conditions, use else if to connect subsequent conditions, avoiding nested if statements which can make code messy:

if (condition1) {
    // Executed when condition1 is true
} else if (condition2) {
    // Executed when condition1 is false but condition2 is true
} else if (condition3) {
    // Executed when conditions 1 and 2 are false but condition3 is true
} else {
    // Executed when all conditions are false
}
  • Note: Conditions are evaluated from top to bottom. Once a condition is true, subsequent conditions are not checked. Thus, conditions should be ordered from broad to specific (e.g., check score >= 90 first, then 80-89, to avoid logical errors).

3. Practical Case 1: Determine Even/Odd Numbers

Requirement: Input an integer and determine if it is even or odd.

Idea:
An integer is even if its remainder when divided by 2 is 0; otherwise, it is odd. Use the % operator (modulus) to check: num % 2 == 0 for even numbers.

Code Example:

#include <iostream>
using namespace std;

int main() {
    int num;
    cout << "Please enter an integer: ";
    cin >> num;  // Read the user's input

    // Check if the number is even
    if (num % 2 == 0) {
        cout << num << " is an even number" << endl;
    } else {
        cout << num << " is an odd number" << endl;
    }

    return 0;
}

Test Runs:
Input 7 → Output: 7 is an odd number;
Input 10 → Output: 10 is an even number.

4. Practical Case 2: Determine Grade Level

Requirement: Input an exam score (0-100) and output the corresponding grade (A/B/C/D/F).
Rules: 90-100 → A; 80-89 → B; 70-79 → C; 60-69 → D; <60 → F.

Idea:
Use else if to check score ranges sequentially, ordered from highest to lowest to avoid misclassification.

Code Example:

#include <iostream>
using namespace std;

int main() {
    int score;
    cout << "Please enter your exam score (0-100): ";
    cin >> score;

    // Check if the score is valid (0-100)
    if (score < 0 || score > 100) {
        cout << "Invalid score! Please enter an integer between 0 and 100." << endl;
    } else if (score >= 90) {  // Check highest score range first
        cout << "Grade: A" << endl;
    } else if (score >= 80) {  // Next highest range
        cout << "Grade: B" << endl;
    } else if (score >= 70) {
        cout << "Grade: C" << endl;
    } else if (score >= 60) {
        cout << "Grade: D" << endl;
    } else {  // Handle failing scores last
        cout << "Grade: F" << endl;
    }

    return 0;
}

Test Runs:
Input 95 → Output: Grade: A;
Input 75 → Output: Grade: C;
Input 55 → Output: Grade: F;
Input 105 → Output: Invalid score! Please enter an integer between 0 and 100..

5. Notes and Common Errors

  1. Condition Expressions Must Be Boolean
    For example, if (a = 5) is incorrect (assignment returns the variable itself, not a boolean). Correct: if (a == 5) (== is a comparison operator returning true/false).

  2. Order of else if
    Always order conditions from broad to specific. Otherwise, logical errors occur. For example, checking score >= 80 before score >= 90 would misclassify 95 as “B” (instead of “A”).

  3. Use of Braces
    Even for a single statement, braces are recommended. For example:

   if (num % 2 == 0)
       cout << "Even";  // Works, but error-prone for future expansion
   else
       cout << "Odd";

Without braces, adding more statements later will cause compilation errors. Always use braces for safety.

  1. Scope of Condition Expressions
    Avoid ambiguous code like if (num = 0) (easy to misread). Use clear, readable expressions.

6. Summary

The if-else statement is C++’s most basic conditional control structure, enabling programs to execute different logic based on conditions. Key points:
- Use if for single conditions, if-else for two choices, and else if for multiple conditions.
- Pay attention to the order of conditions (broad to specific) and expression correctness.
- Familiarize with practical cases (e.g., even/odd checks, grade levels) to build “logical decision-making” skills.

After mastering if-else, you can learn more complex nested conditions (e.g., if inside if-else) or combine with switch statements for multi-branch scenarios.

Xiaoye