C++ If-Else If Ladder

The if-else if ladder in C++ allows you to check multiple conditions sequentially. Only the first condition that evaluates to true executes its block, and the rest are skipped.

1. If-Else If Ladder Example

This example demonstrates how to use multiple conditions using the if-else if ladder.

C++
Example: If-Else If Ladder
#include <iostream>
using namespace std;

int main() {
    int marks = 85;

    if (marks >= 90) {
        cout << "Grade: A" << endl;
    } else if (marks >= 75) {
        cout << "Grade: B" << endl;
    } else if (marks >= 50) {
        cout << "Grade: C" << endl;
    } else {
        cout << "Grade: F" << endl;
    }

    return 0;
}

2. Common Mistakes

Make sure the conditions are ordered from most specific to least specific. Otherwise, some conditions may never be evaluated.

C++
Incorrect ordering example
#include <iostream>
using namespace std;

int main() {
    int marks = 85;

    if (marks >= 50) {
        cout << "Grade: C" << endl; // This will run first and skip higher grades
    } else if (marks >= 75) {
        cout << "Grade: B" << endl;
    }

    return 0;
}

Conclusion

The if-else if ladder is useful for handling multiple sequential conditions in C++. Proper ordering and logical structuring of conditions ensure correct program behavior.