🚀 C++ Programming Lesson 7:
Multi-layer Branching Structure (if-else if-else) – Teaching Programs to Make ‘Multiple Choices’

📚 Course Navigation
1、🤔 What is a Multi-layer Branching Structure? (Real-life ‘Multiple Choice’ Scenarios)2、📝 Syntax and Execution Logic of if-else if-else Statements (The ‘Multi-condition Judgment Framework’ of Programs)3、🌟 Programming Case Studies (From Basics to Practical Applications)4、⚠️ Common Errors and Pitfalls (Avoiding Mistakes in Multi-condition Judgments)5、📢 Next Lesson Preview: switch Statement (Specifically for ‘Value Matching’ Branches)
1. 🤔 What is a Multi-layer Branching Structure? – Real-life ‘Multiple Choice’ Scenarios
In the previous two lessons, we learned about the single branch ‘if… then…’ and the double branch ‘if… then…, else…’, but there are many ‘multiple choice’ scenarios in real life, such as:
- Grade Evaluation: ‘If ≥90 is Excellent, ≥80 is Good, ≥60 is Pass, otherwise Fail’;
- Age Segmentation: ‘If < 3 years is Toddler, 3-6 years is Preschool, 6-12 years is Child, over 12 years is Teenager’;
- Shopping Discounts: ‘If spending ≥1000, reduce 200, ≥500, reduce 80, ≥200, reduce 20, otherwise no discount’.
These scenarios requirejudging multiple conditions and selecting one to execute, which necessitates a multi-layer branching structure – implemented using if-else if-else statements. The core logic is: sequentially judging multiple conditions; as soon as one condition is met, the corresponding code block is executed, and subsequent conditions are not judged; if all conditions are not met, the final else code block is executed.

2. 📝 Syntax and Execution Logic of if-else if-else Statements
(1) Basic Syntax Format
A multi-layer branching structure is like building a ‘multi-condition judgment framework’ for the program, structured as follows:
if (condition1) { // Code block 1 executed when condition1 is true} else if (condition2) { // Code block 2 executed when condition1 is false and condition2 is true} else if (condition3) { // Code block 3 executed when condition1 and condition2 are false and condition3 is true}// ... (more else if can be added as needed)else {// Code block executed when all conditions are false (optional, can be omitted if all cases are covered)}// After executing a code block, jump here to continue execution
(2) Key Components Analysis
- if: Initiates the first condition judgment, the ‘starting point’ of the entire branching structure.
- else if: Adds subsequent condition judgments, with no limit on the number (add as many else if as needed, each must have a new condition expression).
- else: Handles the case where ‘all conditions are false’, is the ‘catch-all’ code block, optional (if previous conditions cover all possibilities, such as ‘score ≥60’ and ‘<60’, else can be omitted).
- Condition Expression: Each condition must return a bool result (true/false), usually composed of relational operators (e.g., score >= 90, age < 3).
(3) Core Execution Logic (‘Short-circuit Judgment’ Principle)
The execution logic of multi-layer branches is crucial, following the ‘once hit, subsequent not judged’ short-circuit principle, with steps as follows:
1. First step: judge ‘condition 1’;
- If condition 1 is true: execute code block 1, skip all subsequent else if and else, directly execute code outside the branching structure;
- If condition 1 is false: proceed to the next step.
2. Second step: judge ‘condition 2’;
- If condition 2 is true: execute code block 2, skip subsequent conditions, directly exit the branch;
- If condition 2 is false: continue to judge the next else if.
3. Third step: sequentially judge the conditions of subsequent else if until the first true condition is found, execute the corresponding code block;4. Fourth step: if all else if conditions are false, execute the else code block (if any);5. Finally: regardless of which code block is executed, jump to continue executing code outside the branching structure.
(4) Syntax Example: Grade Evaluation
Using multi-layer branches for grade evaluation, feel the execution logic:
int score = 75;if (score >= 90) { cout << "Grade Level: Excellent" << endl;} else if (score >= 80) { cout << "Grade Level: Good" << endl;} else if (score >= 60) { cout << "Grade Level: Pass" << endl;} else { cout << "Grade Level: Fail" << endl;} cout << "Evaluation Complete!" << endl;
Execution Process:
- First judge score >= 90 (75≥90? false);
- Then judge score >= 80 (75≥80? false);
- Next judge score >= 60 (75≥60? true), execute the ‘Pass’ code block;
- Skip else, directly execute ‘Evaluation Complete!’, finally output ‘Grade Level: Pass’ and ‘Evaluation Complete!’.
3. 🌟 Programming Case Studies – From Basics to Practical Applications
Case 1: Grade Evaluation System (Basic Application)
Write a program that allows users to input their score and automatically outputs the corresponding grade (Excellent / Good / Pass / Fail):
#include <iostream>using namespace std;int main() { int score; cout << "Please enter your exam score (0-100):"; cin >> score; // Multi-layer branch to judge grade level if (score >= 90 && score <= 100) { // Add range judgment to avoid invalid input over 100 cout << "🎉 Your grade level: Excellent!" << endl; } else if (score >= 80 && score < 90) { cout << "👏 Your grade level: Good!" << endl; } else if (score >= 60 && score < 80) { cout << "✅ Your grade level: Pass!" << endl; } else if (score >= 0 && score < 60) { cout << "❌ Your grade level: Fail, need to improve!" << endl; } else { cout << "⚠️ Your input score is invalid (please enter a number between 0-100)!" << endl; } cout << "Grade evaluation ended!" << endl; return 0;}
Run Scenario 1 (Input 85):
Enter your exam score (0-100): 85
👏 Your grade level: Good!
Grade evaluation ended!
Run Scenario 2 (Input 105):
Enter your exam score (0-100): 105
⚠️ Your input score is invalid (please enter a number between 0-100)!
Grade evaluation ended!
Case Explanation: Each condition has added a ‘range judgment’ (e.g., score >= 80 && score < 90) to avoid invalid input, and the else catch-all handles error cases, making the logic more rigorous.
Case 2: Age Segmentation and Recommended Activities (Practical Scenario)
Based on user input age, determine the age group and recommend corresponding activities:
#include <iostream>using namespace std;int main() { int age; cout << "Please enter your age:"; cin >> age; cout << "Your age group and recommended activities:" << endl; if (age < 3) { cout << "👶 Age Group: Toddler" << endl; cout << "Recommended Activities: Play with rattles, listen to nursery rhymes" << endl; } else if (age >= 3 && age < 6) { cout << "🧸 Age Group: Preschool" << endl; cout << "Recommended Activities: Building blocks, reading picture books, learning simple English" << endl; } else if (age >= 6 && age < 12) { cout << "🎒 Age Group: Elementary School" << endl; cout << "Recommended Activities: Playing soccer, learning programming, participating in science experiments" << endl; } else if (age >= 12 && age < 18) { cout << "📚 Age Group: Teenager" <&& endl; cout << "Recommended Activities: Playing basketball, reading classics, learning an instrument" << endl; } else { cout << "👨🦰 Age Group: Adult" << endl; cout << "Recommended Activities: Fitness, travel, learning new skills" << endl; } return 0;}
Run Result (Input 10):
Please enter your age: 10
Your age group and recommended activities:
🎒 Age Group: Elementary School
Recommended Activities: Playing soccer, learning programming, participating in science experiments
Case Explanation: Each else if condition is ‘continuous and non-overlapping’, ensuring each age corresponds to a unique age group, and the recommended content is practical, reflecting the practical value of multi-layer branches.
Case 3: Shopping Discount Calculation (Combining Arithmetic Operations)
Based on user input spending amount, calculate the corresponding discount amount and final payment amount:
#include <iostream>using namespace std;int main() { double total; // Total spending amount (may have decimals, use double) double discount = 0; // Discount amount, initially 0 cout << "Please enter your total shopping amount (Yuan):"; cin >> total; // Multi-layer branch to judge discount level if (total >= 1000) { discount = 200; // Reduce 200 for spending over 1000 cout << "🎁 You enjoy a discount of 200 for spending over 1000!" << endl; } else if (total >= 500) { discount = 80; // Reduce 80 for spending over 500 cout << "🎁 You enjoy a discount of 80 for spending over 500!" << endl; } else if (total >= 200) { discount = 20; // Reduce 20 for spending over 200 cout << "🎁 You enjoy a discount of 20 for spending over 200!" << endl; } else { cout << "💡 This spending does not reach the discount threshold, no discount~" << endl; } double payment = total - discount; // Calculate final payment amount cout << "Total spending amount:" << total << " Yuan" << endl; cout << "Discount amount:" << discount << " Yuan" << endl; cout << "Final payment amount:" << payment << " Yuan" << endl; return 0;}
Run Result (Input 680):
Please enter your total shopping amount (Yuan): 680
🎁 You enjoy a discount of 80 for spending over 500!
Total spending amount: 680 Yuan
Discount amount: 80 Yuan
Final payment amount: 600 Yuan
Case Explanation: The ‘discount amount’ variable is modified within the branches, and the final payment amount is calculated uniformly at the end, making the code structure clear and balancing branching judgment with arithmetic operations.
4. ⚠️ Common Errors and Pitfalls
Error 1: Condition Order Reversal (Leading to Logical Errors)
// Error Example: Judging grade level, condition order reversedint score = 85;if (score >= 60) { // First judging the low threshold condition, 85≥60 is true, subsequent conditions will not execute cout << "Pass" << endl;} else if (score >= 80) { cout << "Good" << endl; // Will never execute} else if (score >= 90) { cout << "Excellent" << endl; // Will never execute}
Problem: In multi-layer branches, condition judgments have ‘order priority’; if the first judged condition has a broader range (e.g., >=60 includes >=80 and >=90), it will ‘hit first’, causing subsequent more precise conditions to never execute.
Solution:Conditions must be sorted from ‘narrow range, high threshold’ to ‘broad range, low threshold’, for example, first judge >=90, then >=80, finally >=60:
if (score >= 90) { cout << "Excellent"; }else if (score >= 80) { cout << "Good"; }else if (score >= 60) { cout << "Pass"; }
Error 2: Overlapping Conditions (Leading to Ambiguity)
// Error Example: Age segmentation, overlapping conditionsint age = 6;if (age <= 6) { // Age 6 satisfies this condition cout << "Preschool" << endl;} else if (age >= 6) { // Age 6 also satisfies this condition cout << "Elementary School" << endl;}
Problem: age=6 satisfies both <=6 and >=6, but due to the branch being ‘short-circuit judgment’, the first condition (Preschool) will execute first, but in actual demand, age 6 may belong to ‘Elementary School’, leading to logical ambiguity.
Solution:Make conditions ‘continuous and non-overlapping’, using ‘strictly less than’ or ‘strictly greater than’ to define boundaries, for example:
if (age < 6) { cout << "Preschool"; } // <6, does not include 6else if (age >= 6 && age < 12) { cout << "Elementary School"; } // 6≤age<12, includes 6}
Error 3: Omitting else Leading to ‘No Handling’ Situations
// Error Example: Judging grades, omitting else (no handling when score <0)int score = -5;if (score >= 90) { cout << "Excellent"; }else if (score >= 80) { cout << "Good"; }else if (score >= 60) { cout << "Pass"; }else if (score >= 0) { cout << "Fail"; }// When score <0, no code executes, user does not know input is invalid
Problem: If the user inputs an invalid value (e.g., -5), all conditions are false, and without an else catch-all, the program will ‘silently’ do nothing, leaving the user unable to determine if the input is erroneous.
Solution:Add else to handle ‘all other situations’, especially for invalid inputs:
else { cout << "Invalid input! Score should be between 0-100~" << endl;}
Error 4: Forgetting to Write { } Leading to Code Block Scope Errors
// Error Example: No { }, code block scope is confusedint age = 4;if (age < 3) cout << "Toddler" << endl; cout << "Recommended Rattle" << endl; // Not in if code block, will execute regardless of conditionelse if (age >=3 && age <6) cout << "Preschool" << endl; cout << "Recommended Picture Book" << endl; // Not in else if code block, will execute regardless of condition
Problem: Without { }, each if/else if only controls the ‘immediately following first line of code’, the second line will ‘fall out of control’, executing regardless of whether the condition is met.
Solution: Regardless of how many lines are in the code block, { } must be written to clarify the scope:
if (age < 3) { cout << "Toddler" << endl; cout << "Recommended Rattle" << endl;} else if (age >=3 && age <6) { cout << "Preschool" << endl; cout << "Recommended Picture Book" << endl;}
5. 📢 Next Lesson Preview: switch Statement
In this lesson, we learned to use if-else if-else to handle ‘multiple choice’ scenarios, but when the need is to judge ‘whether a variable equals a fixed value’ (such as ‘day of the week’, ‘month’, ‘menu options’), using if-else if-else can become cumbersome.
In the next lesson, we will learn aboutswitch statement – which is specifically used for ‘value matching’ branch scenarios, such as:
- ‘If today is 1 (Monday), output ‘Go to school’; if 2 (Tuesday), output ‘Go to school’; … if 6 (Saturday), output ‘Rest’;’;
- ‘If the user selects 1 (query grades), execute the query function; select 2 (change password), execute the change function’.
The switch statement can make ‘value matching’ code more concise and readable, complementing the multi-layer branching structure. Looking forward to exploring it together in the next lesson! 😉