C++ System Learning Without Textbooks: 03 Conditional Branch Statements

<Conditional Branch Statements>From beginner to expert, from Hello World to ACMAll practical content, no textbooks required!

Course Objective: To enable programs to have “intelligence” and execute different code blocks based on different conditions. This is a key step from simple calculations to logical decision-making.

1. Why are Conditional Branches Needed?

Imagine a scenario:

Writing a program to determine whether the user’s input score is passing.

Without conditional branches, the program can only mechanically execute the same set of actions. But with the <span>if</span> statement, the program can “think”:

if (score >= 60) {    // If the score is greater than or equal to 60, output "Passing"} else {    // Output "Not Passing"}

This is the power of conditional branches; it gives the program the most basic decision-making ability and is the foundation for building complex algorithms.

2. The Core of Conditional Branches: the if Statement

<span>if</span> statements are the most important and commonly used conditional branch statements.

1. Single Branch if Statement

This is the simplest form, used to execute certain operations when a condition is met.

if (condition) {    // If the condition is true, execute this code}

Practical Example 1: Determine Odd or Even

#include <iostream>using namespace std;int main() {    int num;    cin >> num;    if (num % 2 == 0) { // If num divided by 2 has a remainder of 0        cout << num << " is even" << endl;    }    if (num % 2 == 1) { // If num divided by 2 has a remainder of 1        cout << num << " is odd" << endl;    }    return 0;}

<span>Condition</span> Explanation:

<span>Condition</span> is a boolean expression whose result can only be <span>true</span> (true) or <span>false</span> (false). For example, <span>num % 2 == 0</span> is a relational expression used to determine if both sides are equal.

Common Mistake Reminder:

<span>==</span> (equality comparison) and <span>=</span> (assignment) are worlds apart; this is a common mistake for beginners.

Error:

if (num = 0) ...// This assigns 0 to num, and the condition is always false!

Correct:

if (num == 0) ...// This checks if num is equal to 0.

2. Double Branch if-else Statement

When one operation is executed if the condition is met and another operation is executed if it is not met, using <span>if-else</span> is more concise.

if (condition) {    // Execute when the condition is true} else {    // Execute when the condition is false}

Optimizing the Above Example 1:

if (num % 2 == 0) {    cout << num << " is even" << endl;} else { // Otherwise, it must be odd    cout << num << " is odd" << endl;}

3. Multiple Branches: if – else if – else

When multiple conditions need to be evaluated, <span>else if</span> can be used to chain them together.

Practical Example 2: Grade Evaluation

#include <iostream>using namespace std;int main() {    int score;    cin >> score;    if (score >= 90) {        cout << "Excellent" << endl;    } else if (score >= 80) { // 90 > score >= 80        cout << "Good" << endl;    } else if (score >= 70) {        cout << "Average" << endl;    } else if (score >= 60) {        cout << "Passing" << endl;    } else { // If none of the above conditions are met, score < 60        cout << "Not Passing" << endl;    }    return 0;}

Execution Flow:

The program will evaluate conditions from top to bottom. Once a condition is true, it executes the corresponding code block and immediately exits the entire <span>if-else if</span> structure, and subsequent conditions are no longer evaluated.

Common Issues:

The order of conditions is important. If <span>if (score >= 60)</span> is placed first, then any score greater than 60 will enter the “Passing” branch, and the “Good” and “Excellent” conditions will not be evaluated. Therefore, conditions should be arranged from strict to lenient (or vice versa).

In-Class Test (5 Minutes)

Please write a program that inputs an integer and determines whether it is positive, negative, or zero.

(Think about whether to check for 0 first or check for positive/negative first? Which logic is clearer? Answer will be provided after class)

3. switch Statement

<span>switch</span> statements are used to execute different code branches based on the value of an integer or enumeration type expression. It is particularly suitable for handling “multiple choice” scenarios.

Syntax Structure:

switch (expression) {    case constant1:        // code block 1        break;    case constant2:        // code block 2        break;    ...    default:        // default code block (optional)        break;}

Practical Example 3: Simple Calculator

#include <iostream>using namespace std;int main() {    char op; // operator    int a, b;    cin >> a >> op >> b;    switch (op) { // Select based on the value of operator op        case '+':            cout << a + b << endl;            break; // Must use break to exit switch        case '-':            cout << a - b << endl;            break;        case '*':            cout << a * b << endl;            break;        case '/':            if (b != 0) {                cout << a / b << endl; // Note integer division            } else {                cout << "Denominator cannot be 0!" << endl;            }            break;        default: // If op is not one of +, -, *, /            cout << "Unsupported operator!" << endl;            break;    }    return 0;}

Common Mistake Reminder:<span>Importance of break</span>

<span>break</span> statements are used to exit the entire <span>switch</span> block. If you forget to write <span>break</span>, the program will continue to execute the next <span>case</span> code until it encounters a <span>break</span> or the end of the <span>switch</span> block. This is called case fall-through.

Unless you intentionally need case fall-through (for example, when multiple cases share the same code), always write a <span>break</span> after each case.

Comparison with if: <span>switch</span> can only perform equality checks, while <span>if</span> can handle more complex range checks (e.g., <span>score >= 80</span>). Which to choose depends on your needs.

4. Summary and Key Points of This Lesson

<span>if</span> is versatile, used for executing paths based on conditions (true/false).

<span>switch</span> is efficient, making code clearer when needing to evaluate different discrete values of the same variable.

Relational Operators (<span>==</span>, <span>!=</span>, <span>></span>, <span><</span>, <span>>=</span>, <span><=</span>) and Logical Operators (<span>&&</span> – and, <span>||</span> – or, <span>!</span> – not) are the foundation for constructing conditions.

The most common mistake: writing the equality comparison <span>==</span> as an assignment <span>=</span>.

Homework

Homework Objective: To proficiently use conditional branch statements to solve practical problems.

Assignment 1: Basic Consolidation (Complete in local environment or Online GDB)

  1. Absolute Value: Input an integer and output its absolute value.

  2. Leap Year Determination: Input a year and determine if it is a leap year. Leap year rules: A year that is divisible by 4 but not by 100, or divisible by 400.

Assignment 2: OJ Practice (Submit on Luogu)

  1. [P5710 【Deep Foundation 3. Example 2】 Properties of Numbers: This problem contains multiple condition checks, making it ideal for practice.

  2. [P5711 【Deep Foundation 3. Example 3】 Leap Year Determination: Directly apply the leap year rules.

  3. [P5712 【Deep Foundation 3. Example 4】 Apples: Involves simple pluralization of the word (1 apple, multiple apples).

  4. (Challenge Problem) [P1424 Xiaoyu’s Electricity Bill: Requires piecewise calculation, a classic application of conditional branches.

Homework Answers

In-Class Test Answers:

#include <iostream>using namespace std;int main() {    int num;    cin >> num;    if (num > 0) {        cout << "Positive" << endl;    } else if (num < 0) {        cout << "Negative" << endl;    } else {        cout << "Zero" << endl;    }    return 0;}// Check for positive/negative first, then use else for zero, clear logic.

Homework Answer Hints:

Assignment 1:

  1. Absolute Value Program:

    #include <iostream>using namespace std;int main() {    int num;    cin >> num;    if (num >= 0) {        cout << num << endl;    } else {        cout << -num << endl; // If negative, take negative to get positive    }    return 0;}
  2. Leap Year Determination Program:

    #include <iostream>using namespace std;int main() {    int year;    cin >> year;    // Directly translate the leap year rules into conditions    if ((year % 4 == 0 && year % 100 != 0) || (year % 400 == 0)) {        cout << "Is a leap year" << endl;    } else {        cout << "Is not a leap year" << endl;    }    return 0;}// Note: Logical AND (&&) has higher precedence than logical OR (||), but adding parentheses makes logic clearer.

OJ Problem Key Points:

P5710: The problem has two properties that need to be independently checked, outputting two boolean values (1/0).

P5711: Directly use the leap year determination logic from Assignment 1.

P5712: Very simple, check if the input apple count is 1, then decide whether to add “s” to the word “apple”.

P1424: This is a classic piecewise function problem. It requires applying different electricity prices based on the range of electricity consumption (e.g., 0-150 degrees, 151-400 degrees, above 401 degrees). This is the perfect use case for the <span>if-else if</span> structure.

Be sure to familiarize yourself with various condition combinations through extensive practice.

In the next class, we will learn about:

Loop Statements

If you have any questions, feel free to chat in the comments!

Follow YunJie Algorithm, no textbooks needed, just a few clicks to learn programming systematically!

Leave a Comment