
Let’s think it through · Start with a story
Take an umbrella if it rains; wear a hat if it does not. The girl wants the robot to know what to do in either case.
Break down the process
- CheckIs it raining today?
- TrueTake an umbrella
- FalseWear a hat
- Join back upContinue going out
else provides an alternative path when an if condition is false. In one if/else statement, only one branch runs.
You can picture the branches as two diverging paths. After each path handles its action, they can rejoin for the steps that follow.
01Is an if statement enough?
If we need to handle both “pass” and “fail,” we can use else:
if (score >= 60) {
std::cout << "Pass";
} else {
std::cout << "Fail";
}
02Why does if...else take only one path?
For a single decision:
Run the if branch
Run the else branch
Both branches do not run during the same if...else decision.
03Does else have a condition of its own?
No. else means: “If the preceding if condition is not true, come here.”
If you need to test another condition, use else if.
04Which if does else belong to?
if (a > 0) {
if (b > 0) {
std::cout << "A";
} else {
std::cout << "B";
}
}
Here, else belongs to the inner if (b > 0).
05Is if...else the same as two if statements?
if...else
Only one branch is selected for a single decision.
Two separate if statements
Both conditions are evaluated independently, so both code blocks might run.
06How can you trace a decision?
int score = 75;
if (score >= 60) {
std::cout << "Pass";
} else {
std::cout << "Fail";
}
What you have learned
if...elserepresents a choice between two paths.- If the condition is true, run if; if false, run else.
- Only one branch runs for a single decision.
- else does not have a condition of its own.
- Braces make nested if statements clearer.
Next: How Do We Handle Multiple Conditions?
Your turn
If it rains today, will this if/else both make you take an umbrella and wear a hat?
Have an answer? Click to see the explanation
Under the rules in this example, only the umbrella branch runs. To do both actions, you would need to write the appropriate actions separately.