How if and else Choose a Path
One reminder, two paths
The garden club needs one clothing reminder for the current temperature. An if uses a condition to choose whether a block runs. An else provides the alternative when that condition is false.
#include <stdio.h>
int main(void) {
int temperature = 8;
if (temperature < 10) {
printf("Bring a coat\n");
} else {
printf("Light layers are fine\n");
}
printf("Check complete\n");
return 0;
}
Trace the value 8. 8 < 10 is true, so the first block prints Bring a coat. C skips the else block, then prints Check complete because that call is outside both branches.
The parentheses hold the condition. The braces hold the statements for each branch. Use braces even for one statement so that another statement added later stays in the intended block.
More than two choices
For cold, mild, and warm messages, divide the remaining temperatures with else if. C checks the chain from top to bottom and runs the first matching branch; the final else handles temperatures that failed every earlier test.
#include <stdio.h>
int main(void) {
int temperature = 16;
if (temperature < 10) {
printf("Cold\n");
} else if (temperature < 20) {
printf("Mild\n");
} else {
printf("Warm\n");
}
return 0;
}
An else if is checked only if the preceding condition was false. Here 16 fails < 10 but passes < 20, so the program prints Mild and skips the final else.
| Temperature | First test: < 10 | Next test: < 20 | Message |
|---|---|---|---|
| 9 | True | Not reached | Cold |
| 10 | False | True | Mild |
| 19 | False | True | Mild |
| 20 | False | False | Warm |
Only the first matching branch runs. Run both examples and compare their fixed values with the table. In an editable exercise, test just below, exactly at, and just above a threshold: that is where < and <= make a difference.