0
0
C++programming~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 what to do based on user input with many options.
When you want to handle different ranges of numbers differently.
When you want to pick one action out of many possible conditions.
When simple if-else is not enough because there are many conditions to check.
Syntax
C++
if (condition1) {
    // code if condition1 is true
} else if (condition2) {
    // code if condition2 is true
} else if (condition3) {
    // code if condition3 is true
} else {
    // code if none of the above conditions are true
}

The conditions are checked from top to bottom.

Only the first true condition's code runs; the rest are skipped.

Examples
Checks if a number is positive, zero, or negative.
C++
int num = 10;
if (num > 0) {
    // positive number
} else if (num == 0) {
    // zero
} else {
    // negative number
}
Decides message based on grade letter.
C++
char grade = 'B';
if (grade == 'A') {
    // excellent
} else if (grade == 'B') {
    // good
} else if (grade == 'C') {
    // average
} else {
    // needs improvement
}
Sample Program

This program asks for a score and prints the grade using an else-if ladder.

C++
#include <iostream>
using namespace std;

int main() {
    int score;
    cout << "Enter your score (0-100): ";
    cin >> score;

    if (score >= 90) {
        cout << "Grade: A" << endl;
    } else if (score >= 80) {
        cout << "Grade: B" << endl;
    } else if (score >= 70) {
        cout << "Grade: C" << endl;
    } else if (score >= 60) {
        cout << "Grade: D" << endl;
    } else {
        cout << "Grade: F" << endl;
    }

    return 0;
}
OutputSuccess
Important Notes

Make sure conditions are ordered from most specific to least specific to avoid wrong results.

The else part is optional but good to handle unexpected cases.

Summary

Else-if ladder checks multiple conditions one by one.

Only the first true condition runs its code.

Use it when you have many choices to decide between.