C else-if Ladder
In this page:
What is an else-if Ladder?
An else-if ladder chains multiple conditions together so they're checked in order, and as soon as one evaluates to true, its block runs and every later condition in the chain is skipped without being checked at all.
Example: What is an else-if Ladder?
#include <stdio.h>
int main() {
int score = 75;
if (score >= 90) {
printf("A");
} else if (score >= 70) {
printf("B");
} else {
printf("C");
}
return 0;
}
Login to try C/C++/Java/PHP code in the editor
Grading System
Assigning letter grades based on numeric score ranges is a textbook use of an else-if ladder -- each condition tests a lower boundary, and because they're checked in order, only the first matching range applies.
Example: Grading System
#include <stdio.h>
int main() {
int score = 82;
if (score >= 90) {
printf("A");
} else if (score >= 80) {
printf("B");
} else if (score >= 70) {
printf("C");
} else {
printf("F");
}
return 0;
}
Login to try C/C++/Java/PHP code in the editor
Number Classification
You can classify a number as positive, negative, or zero with three chained conditions in an else-if ladder, which reads far more clearly than three separate, unrelated if statements checking the same variable.
Example: Number Classification
#include <stdio.h>
int main() {
int n = -5;
if (n > 0) {
printf("Positive");
} else if (n < 0) {
printf("Negative");
} else {
printf("Zero");
}
return 0;
}
Login to try C/C++/Java/PHP code in the editor
Age Categories
Grouping ages into categories like child, adult, and senior with an else-if ladder keeps the boundaries between categories explicit and easy to adjust later, since each range is defined in one place.
Example: Age Categories
#include <stdio.h>
int main() {
int age = 45;
if (age < 13) {
printf("Child");
} else if (age < 65) {
printf("Adult");
} else {
printf("Senior");
}
return 0;
}
Login to try C/C++/Java/PHP code in the editor
Temperature Guides
Classifying temperature ranges (cold, mild, hot) is a natural fit for an else-if ladder, since each condition only needs to check one boundary given that earlier, more extreme ranges have already been ruled out by prior checks.
Example: Temperature Guides
#include <stdio.h>
int main() {
int temp = 85;
if (temp < 50) {
printf("Cold");
} else if (temp < 80) {
printf("Mild");
} else {
printf("Hot");
}
return 0;
}
Login to try C/C++/Java/PHP code in the editor
Chapter Quiz — Complete all 11 topics to unlock
0/11 topics done
Complete these topics first: