Make decisions without making a maze
Use if, else-if, switch, and short-circuit logic to express mutually exclusive and independent decisions.
After this lesson
You should be able to
- Choose between independent if statements and an if/else-if chain.
- Write conditions that handle boundaries exactly once.
Independent or exclusive?
Use separate if statements when multiple actions may all happen. Use an if/else-if/else chain when exactly one branch should be selected. The first true condition in the chain wins, so order conditions from specific to general.
A switch is useful when one integral expression is compared with several constant cases. Each case normally needs break; otherwise execution falls through to the next case. Fall-through can be intentional, but it should be obvious.
Boundaries and short-circuiting
For a valid percentage, 0 and 100 are usually included: score >= 0 && score <= 100. The && operator evaluates its right side only when the left side is true. The || operator evaluates its right side only when the left side is false.
Short-circuiting can protect an operation. In denominator != 0 && numerator / denominator > 2, division happens only when the denominator is nonzero.
if (score < 0 || score > 100) {
printf("Invalid score\n");
} else if (score >= 90) {
printf("A\n");
} else if (score >= 75) {
printf("B\n");
} else if (score >= 60) {
printf("C\n");
} else {
printf("Needs improvement\n");
}Try it yourself
Write a condition that accepts an age from 18 through 25, inclusive.
Need a hint?
Both the lower and upper bound must be true.
Check the worked solution
Use age >= 18 && age <= 25. Using || would accept almost every number.
if (age >= 18 && age <= 25) {
printf("Eligible\n");
}Quick check
Why is an else-if chain suitable for assigning one grade?
Why this lesson exists
Syllabus mapping
Conditionals · Branching · Logical operators
Maps to course outcomes CO1, CO2, CO3.