Introduction
An else-if ladder helps you check many conditions one after another. It lets your program choose the right action based on different situations.
An else-if ladder helps you check many conditions one after another. It lets your program choose the right action based on different situations.
if (condition1) { // code to run if condition1 is true } else if (condition2) { // code to run if condition2 is true } else if (condition3) { // code to run if condition3 is true } else { // code to run if none of the above conditions are true }
Conditions are checked from top to bottom.
Only the first true condition's code runs, then the rest are skipped.
if (score >= 90) { printf("Grade A\n"); } else if (score >= 80) { printf("Grade B\n"); } else { printf("Grade C or below\n"); }
if (temperature > 30) { printf("It's hot\n"); } else if (temperature > 20) { printf("It's warm\n"); } else if (temperature > 10) { printf("It's cool\n"); } else { printf("It's cold\n"); }
This program asks for your age and tells you which age group you belong to using an else-if ladder.
#include <stdio.h> int main() { int age; printf("Enter your age: "); scanf("%d", &age); if (age < 13) { printf("You are a child.\n"); } else if (age < 20) { printf("You are a teenager.\n"); } else if (age < 60) { printf("You are an adult.\n"); } else { printf("You are a senior.\n"); } return 0; }
Make sure conditions do not overlap in a confusing way.
The else part is optional but useful for handling all other cases.
Else-if ladder checks multiple conditions one by one.
Only the first true condition runs its code.
Use else to catch all other cases not covered by previous conditions.
else-if ladder do in C programming?int x = 15;
if (x < 10) {
printf("Less than 10\n");
} else if (x < 20) {
printf("Less than 20\n");
} else {
printf("20 or more\n");
}int num = 5;
if (num > 10)
printf("Greater than 10\n");
else if num > 0
printf("Positive number\n");
else
printf("Zero or negative\n");Pass the test and this pattern moves unknown