Else-if ladders for multiple conditions
What you'll learn: How to chain multiple tests together to handle several different scenarios in a single decision-making block.
The problem with just "If" and "Else"
So far, you’ve learned how to handle a fork in the road: if a condition is true, do A; otherwise, do B. But life isn't always a simple "yes" or "no." Imagine you are checking a student’s grade. A score isn't just "Pass" or "Fail"; it could be an A, B, C, D, or F.
If you used only independent if statements, the computer would check every single one, even after it found a match. If you used nested else blocks, your code would quickly drift off the right side of the screen in a messy zigzag.
The Else-If solution
The else if ladder allows you to test multiple conditions in order. The computer starts at the top and works its way down. As soon as it finds a condition that is true, it runs that specific block of code and then jumps to the very end of the entire ladder, skipping all other tests.
Think of it like a series of locked doors. You have a ring of keys and try them one by one. The moment one key unlocks a door, you walk through it and stop looking at the other keys.
See it in action
Here is how you handle multiple temperature ranges using an else if ladder:
#include <stdio.h>
int main() {
int temp = 25;
if (temp > 30) {
printf("It's scorching outside.\n");
} else if (temp > 20) {
printf("It's a beautiful day.\n");
} else if (temp > 10) {
printf("It's a bit chilly.\n");
} else {
// This runs only if NONE of the above were true
printf("It's freezing!\n");
}
return 0;
}
Why order matters
In an else if ladder, the first match wins. If we had put else if (temp > 10) at the very top, a temperature of 25 would have triggered that block immediately, and the computer would have never checked if it was also over 20 or 30. Always arrange your conditions from the most specific to the most general to ensure the logic flows correctly.
Key takeaway
Use else if to link multiple exclusive options together, ensuring only one block of code executes out of many possibilities.