0
0
Cprogramming~5 mins

Else–if ladder in C

Choose your learning style9 modes available
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.

When you want to check multiple choices, like grading scores (A, B, C, etc.).
When you need to decide different actions based on user input.
When you want to handle different ranges of numbers with different messages.
When you want to pick one option out of many possibilities.
Syntax
C
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.

Examples
This example checks a score and prints the grade.
C
if (score >= 90) {
    printf("Grade A\n");
} else if (score >= 80) {
    printf("Grade B\n");
} else {
    printf("Grade C or below\n");
}
This example prints a message based on temperature ranges.
C
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");
}
Sample Program

This program asks for your age and tells you which age group you belong to using an else-if ladder.

C
#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;
}
OutputSuccess
Important Notes

Make sure conditions do not overlap in a confusing way.

The else part is optional but useful for handling all other cases.

Summary

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.