🚀 C++ Programming Lesson 6: Multi-Branch Structures (if-else Statements) – Teaching Programs to Make ‘Two-Way Choices’

📚 Course Navigation
1、🤔 What is a Multi-Branch Structure? (Two-Way Choice Scenarios in Life)2、📝 Syntax and Execution Logic of if-else Statements (The Program’s ‘Two-Way Judgment Framework’)3、🌟 Programming Case Studies (Applications from Basic to Advanced)4、⚠️ Common Errors and Pitfalls (Avoiding Logical Errors in Judgments)5、📢 Next Lesson Preview: Multi-Layer Branch Structures (if-else if-else Statements)
1. 🤔 What is a Multi-Branch Structure? – Two-Way Choice Scenarios in Life
A single-branch structure is ‘if… then…’, while a multi-branch structure (if-else statement) is ‘if… then…, else…’, which can cover all ‘either-or’ scenarios in life, such as:
- ‘If it doesn’t rain tomorrow, then go to the park; otherwise, go to the library to read.’
- ‘If the exam score ≥ 60, then pass; otherwise, fail.’
- ‘If there are enough apples to distribute, then give one to each person; otherwise, inform everyone that there are not enough.’
In programming, a multi-branch structure is implemented using the if-else statement, with the core logic being: If the condition is true (bool is true), execute one block of code; if the condition is false (bool is false), execute another block of code – one of the two code blocks must execute, neither will execute both, nor will both fail to execute.
2. 📝 Syntax and Execution Logic of if-else Statements
(1) Basic Syntax Format
The if-else statement acts like a ‘two-way judgment framework’ for the program, structured as follows:
if (condition expression) { // Code block executed when condition is true (Code Block A)} else { // Code block executed when condition is false (Code Block B)} // Regardless of whether A or B is executed, the code here will continue to execute
(2) Key Components Analysis
- if Keyword: Initiates the condition judgment, functioning the same as in a single-branch structure.
- (Condition Expression): Must return a bool result (true/false), usually composed of relational operators (e.g., score >= 60, age > 12).
- else Keyword: Indicates ‘otherwise’, which is the core of the multi-branch structure, used to define the ‘code block when the condition is false’, must immediately follow the } of if, and cannot be used alone.
- Two Code Blocks:
- Code Block A (inside if): Executed when the condition is true;
- Code Block B (inside else): Executed when the condition is false;
- The two code blocks are mutually exclusive, only one can execute.
- Execution Logic (Three-Step Method):
- Step 1: Calculate the result of the ‘condition expression’ (true or false);
- Step 2: If the result is true, execute Code Block A, skip Code Block B;
- Step 3: If the result is false, skip Code Block A, execute Code Block B;
- Finally, regardless of which code block is executed, continue executing the code after the if-else statement.
(3) Syntax Example: Judging Whether the Score is Passing
Using the if-else statement to judge the score, output different content for passing and failing:
int score = 55;if (score >= 60) { cout << "Congratulations! Your score has passed!" << endl; // Executed when condition is true} else { cout << "Unfortunately, your score has not passed, you need to work harder!" << endl; // Executed when condition is false}cout << "Score judgment completed!" << endl; // This will execute regardless of the result
Execution Process:
- The condition score >= 60 results in false, so skip Code Block A and execute Code Block B;
- Then execute cout << “Score judgment completed!”, ultimately outputting two lines of content.
If score = 70:
- The condition result is true, execute Code Block A, skip Code Block B, output “Congratulations…” and “Judgment completed”.
3. 🌟 Programming Case Studies – Applications from Basic to Advanced
Case 1: Judging Whether Age Meets Movie Watching Conditions (Two-Way Feedback)
The cinema stipulates ‘Age ≥ 12 can watch a certain movie, otherwise must be accompanied by a parent’, using if-else to implement two-way prompts:
#include <iostream>using namespace std;int main() { int age; cout << "Please enter your age:"; cin >> age; // Two-way judgment: meet the condition can watch alone, otherwise must be accompanied if (age >= 12) { cout << "Your age meets the requirements, you can watch this movie alone!" << endl; } else { cout << "Your age does not meet the requirements, you need to watch with a parent!" << endl; } cout << "Movie watching qualification judgment completed!" << endl; return 0;}
Run Scenario 1 (Input 15):
Please enter your age: 15
Your age meets the requirements, you can watch this movie alone!
Movie watching qualification judgment completed!
Run Scenario 2 (Input 10):
Please enter your age: 10
Your age does not meet the requirements, you need to watch with a parent!
Movie watching qualification judgment completed!
Case Explanation: Regardless of whether the age meets the standard, clear feedback is provided, reflecting the advantage of the multi-branch structure’s ‘two-way coverage’.
Case 2: Judging Whether an Integer is Even or Odd
Using if-else combined with modulus operation to determine whether a number is even or odd (non-even is odd, perfectly fitting two-way judgment):
#include <iostream>using namespace std;int main() { int num; cout << "Please enter an integer:"; cin >> num; // Condition: num divided by 2 remainder is 0 (even), otherwise odd if (num % 2 == 0) { cout << num << " is even!" << endl; cout << "Even numbers can be divided by 2, such as 2, 4, 6..." << endl; } else { cout << num << " is odd!" << endl; cout << "Odd numbers leave a remainder of 1 when divided by 2, such as 1, 3, 5..." << endl; } cout << "Odd-even judgment completed!" << endl; return 0;}
Run Result (Input 9):
Please enter an integer: 9
9 is odd!
Odd numbers leave a remainder of 1 when divided by 2, such as 1, 3, 5...
Odd-even judgment completed!
Case Explanation: The ‘even’ and ‘odd’ of integers are mutually exclusive, using if-else perfectly covers all situations, with rigorous logic.
Case 3: Judging Whether the Number of Apples is Sufficient for Distribution (Calculating Surplus or Shortage)
There are 30 students in the class, each student receives 1 apple, using if-else to judge ‘sufficient’ and calculate surplus, or ‘insufficient’ and calculate shortage:
#include <iostream>using namespace std;int main() { int apple_count; const int student_num = 30; // Fixed number of students cout << "Please enter the total number of apples:"; cin >> apple_count; if (apple_count >= student_num) { // Sufficient: calculate remaining apples int remaining = apple_count - student_num; cout << "The number of apples is sufficient!" << endl; cout << "After giving each of the " << student_num << " students 1 apple, there are still " << remaining << " apples left!" << endl; } else { // Insufficient: calculate shortage of apples int shortage = student_num - apple_count; cout << "The number of apples is not enough!" << endl; cout << "After giving each of the " << student_num << " students 1 apple, there are still " << shortage << " apples needed!" << endl; } cout << "Apple distribution plan completed!" << endl; return 0;}
Run Result (Input 25):
Please enter the total number of apples: 25
The number of apples is not enough!
After giving each of the 30 students 1 apple, there are still 5 apples needed!
Apple distribution plan completed!
Case Explanation: By adding calculation logic in the code block, the multi-branch structure can not only ‘judge’ but also ‘process data’, making its functionality richer.
4. ⚠️ Common Errors and Pitfalls
Error 1: Extra Semicolon After else
int score = 50;if (score >= 60) { cout << "Passed!" << endl;} else; { // Error: extra semicolon after else, causing the code block to be unrelated to else cout << "Not passed!" << endl;}
Problem: The semicolon causes else to ‘end early’, making the following { } an independent code block, which will execute regardless of whether the condition is met, and may even cause an error.
Solution: Never write a semicolon after else, directly follow with {.
Error 2: Incorrect Position of else (Not Immediately Following the } of if)
int age = 8;if (age >= 12) { cout << "Can watch alone" << endl;}cout << "Judging..." << endl; // Error: else must immediately follow the } of if, cannot insert other codeelse { cout << "Must be accompanied by a parent" << endl;}
Problem: else must be ‘bound’ to if, inserting other code in between will cause the compiler to report an error, thinking else is ‘orphaned’.
Solution: else must immediately follow the } of if, no other code can be in between.
Error 3: Incomplete Logic in Condition Expression (Omitted Cases)
// Error Example: Judging whether a number is greater than 5, but wanting to cover the case of 'equal to 5'int num = 5;if (num > 5) { cout << "Number is greater than 5" << endl;} else { cout << "Number is less than 5" << endl; // Error: 5 is neither greater than 5 nor less than 5, yet outputs 'less than 5'
: The condition num > 5 does not cover the case of ‘equal to 5’, leading to the else incorrectly including the ‘equal to 5’ scenario.
Solution: Adjust the condition according to the requirements, such as changing it to num >= 5, or further judging in else (subsequent multi-layer branches will be learned), ensuring logic covers all cases.
Error 4: Confused Scope of Code Blocks (Forgetting to Write { })
int num = 3;if (num % 2 == 0) cout << num << " is even" << endl; cout << "Even numbers can be divided by 2" << endl; // Error: this line is not in the if code blockelse cout << num << " is odd" << endl; cout << "Odd numbers leave a remainder of 1" << endl; // Error: this line is not in the else code block
Problem: Without { }, if only controls the first line of code, else only controls the first line of code, the second line of code will execute regardless of the condition, leading to confused logic.
Solution: Regardless of how many lines are in the code block, always write { }, clearly defining the scope:
if (num % 2 == 0) { cout << num << " is even" << endl; cout << "Even numbers can be divided by 2" << endl;} else { cout << num << " is odd" << endl; cout << "Odd numbers leave a remainder of 1" << endl;}
5. 📢 Next Lesson Preview: Multi-Layer Branch Structures (if-else if-else Statements)
In this lesson, we learned to use if-else statements to handle ‘either-or’ scenarios, but there are more complex ‘multi-choice’ scenarios in life, such as:
- ‘If the score ≥ 90, it is excellent; if ≥ 80, it is good; if ≥ 60, it is passing; otherwise, it is failing.’
- ‘If age < 3 years, drink formula; 3-6 years, drink milk; over 6 years, drink soy milk.’
In the next lesson, we will learnMulti-Layer Branch Structures (if-else if-else Statements), which will allow the program to judge multiple conditions and choose one to execute from multiple options, making the program’s ‘selection ability’ more flexible and powerful! Looking forward to exploring together in the next lesson! 😉
