else-if Ladder
In C, the else-if ladder is used when you need to check multiple conditions one after another. It is a more structured way to handle multiple options instead of using many separate if statements.
Syntax:
if (condition1) {
// code runs if condition1 is true
} else if (condition2) {
// code runs if condition2 is true
} else if (condition3) {
// code runs if condition3 is true
} else {
// code runs if none of the above conditions are true
}
Example:
#include <stdio.h>
int main() {
int marks = 68;
if (marks >= 90) {
printf("Grade A\n");
} else if (marks >= 75) {
printf("Grade B\n");
} else if (marks >= 60) {
printf("Grade C\n");
} else if (marks >= 40) {
printf("Grade D\n");
} else {
printf("Fail\n");
}
return 0;
}
In this program, the value of marks is checked against several ranges. Only the first true condition's block will run.
How it Works:
- The program checks conditions from top to bottom.
- As soon as it finds a true condition, it runs that block and skips the rest.
- If no condition is true, the
elseblock (if present) will run.
Summary
The else-if ladder is useful when you have multiple possible conditions and only one should be executed. It helps keep your code organized and easy to read. 🔁