Branching statements are decision-making tools in programming that allow a program to execute different operations based on various conditions, achieving true intelligent processing.
π Why Do We Need Branching Statements?
Imagine scenarios in life where choices must be made:
- If it rains, take an umbrella
- If the score β₯ 90, grade it as A
- If itβs a weekday, go to work
Programs also need to make decisions based on conditions, which is the role of branching statements!
π§© The Three Major Branching Statements in C++
1. if Statement: Basic Condition Check
Syntax Structure:
if (condition_expression) {
// Code to execute if the condition is true
}
Example: Age Verification
int age = 20;
if (age >= 18) {
cout << "You are an adult, you may enter!" << endl;
}
2. if-else Statement: A Two-Way Decision
Syntax Structure:
if (condition_expression) {
// Execute if the condition is true
} else {
// Execute if the condition is false
}
Example: Odd or Even Number Check
int num = 7;
if (num % 2 == 0) {
cout << num << " is even" << endl;
} else {
cout << num << " is odd" << endl;
}
3. if-else if Ladder: Multi-Condition Selection
Syntax Structure:
if (condition1) {
// Execute if condition1 is true
} else if (condition2) {
// Execute if condition2 is true
} else if (condition3) {
// Execute if condition3 is true
} else {
// Execute if none of the conditions are met
}
Example: Grade Evaluation
int score = 85;
if (score >= 90) {
cout << "A" << endl;
} else if (score >= 80) {
cout << "B" << endl;
} else if (score >= 70) {
cout << "C" << endl;
} else if (score >= 60) {
cout << "D" << endl;
} else {
cout << "E" << endl;
}
π switch Statement: A Multi-Branch Tool
When you need to execute different operations based on the different values of a variable, switch is more concise and efficient than if-else.
Syntax Structure:
switch (expression) {
case value1:
// Code block 1
break;
case value2:
// Code block 2
break;
...
default:
// Default code block
}
Example: Weekday Check
int day = 3;
switch (day) {
case 1:
case 2:
case 3:
case 4:
case 5:
cout << "Weekday" << endl;
break;
case 6:
case 7:
cout << "Weekend" << endl;
break;
default:
cout << "Invalid input" << endl;
}
Key Points for Using switch:
<span><span>break</span></span>statement is used to exit the switch block (otherwise it will continue to execute the next case)<span><span>default</span></span>handles unmatched cases- The expression must be of integer or enumeration type
- Multiple cases can share the same code block
β¨ Ternary Operator: A Concise Conditional Expression
Syntax Structure:
condition ? expression1 : expression2
Example: Finding the Maximum Value
int a = 5, b = 8;
int max = (a > b) ? a : b;
cout << "The maximum value is: " << max << endl;
π§ The Underlying Logic of Branching Statements
When a computer executes branching statements:
- Calculate the condition expression
- If the result is true (non-zero), execute the if block
- If the result is false (zero), execute the else block (if present)
- In switch, jump to the matching case label to execute
Image
Code
π» Comprehensive Application: Smart Weather Assistant
#include<iostream>
#include<string>
using namespace std;
int main(){
int temperature;
string weather;
cout << "Please enter the current temperature:";
cin >> temperature;
cout << "Please enter the weather condition (sunny/rain/snow/fog):";
cin >> weather;
cout << "Suggestion:";
// Temperature check
if (temperature > 30) {
cout << "It's hot, ";
} else if (temperature < 10) {
cout << "It's cold, ";
} else {
cout << "The temperature is suitable, ";
}
// Weather check
if (weather == "sunny") {
cout << "It's suggested to go out, remember to apply sunscreen!";
} else if (weather == "rain") {
cout << "It's suggested to take an umbrella, be careful of moisture!";
} else if (weather == "snow") {
cout << "It's suggested to wear non-slip shoes, be careful to keep warm!";
} else if (weather == "fog") {
cout << "It's suggested to reduce going out, pay attention to traffic safety!";
} else {
cout << "Unknown weather, please be cautious when traveling!";
}
return 0;
}
Run Example:
Enter the current temperature: 25
Enter the weather condition (sunny/rain/snow/fog): sunny
Suggestion: The temperature is suitable, it's suggested to go out, remember to apply sunscreen!
π Best Practices for Branching Statements
-
Keep condition expressions concise:
// Not recommended if (isValid == true && count > 0 || flag != false) // Recommended if (isValid && count > 0) -
Avoid deep nesting:
// Not recommended: deep nesting if (condition1) { if (condition2) { if (condition3) { // Code } } } // Recommended: use logical operators if (condition1 && condition2 && condition3) { // Code } -
Don’t forget break in switch:
switch (value) { case1: cout << "Case 1"; break; // Necessary! case2: cout << "Case 2"; // Missing break will continue to execute case 3! case3: cout << "Case 3"; break; } -
Use enums to enhance readability:
enum Season {SPRING, SUMMER, AUTUMN, WINTER}; Season current = SUMMER; switch (current) { case SPRING: // More readable than using numbers directly ... }
π Summary and Improvement
Branching statements are fundamental in C++ programming; mastering them allows your programs to:
- Respond differently based on input
- Handle various possible situations
- Implement complex business logic
- Create smarter applications
Scan the code to join the γima Knowledge Baseγ for more computer science knowledge.
