Step 2 of 6
else if chains
When there are more than two possibilities, chain conditions with else if. C tests them from top to bottom and runs the block of the first condition that's true, then skips everything else in the chain. The final else catches whatever is left.
#include <stdio.h>
int main(void) {
int speed;
scanf("%d", &speed);
if (speed > 130) {
printf("way too fast\n");
} else if (speed > 100) {
printf("too fast\n");
} else if (speed >= 60) {
printf("fine\n");
} else {
printf("slow\n");
}
return 0;
}
115
too fast
115 is not over 130, so the first test fails. It is over 100, so the second block runs, and C doesn't even look at the remaining conditions.
Order matters
Because only the first match runs, put the most specific or extreme conditions first. If speed >= 60 came first, a speed of 150 would print fine, because 150 is also at least 60. When conditions are ordered from highest to lowest like this, each later test can rely on the earlier ones having failed: inside the speed > 100 branch you already know the speed is at most 130.
Braces
With a single statement, braces are technically optional (if (x) printf("hi\n");), but always writing them prevents a classic bug: adding a second line later and not noticing it isn't inside the if.
Your turn: read a player's kill count for a round and print:
ACEfor 5 or moremulti-killfor 2 to 4onefor exactly 1nonefor 0