C++ Else If Statement

The else if statement in C++ allows you to test multiple conditions sequentially. It is used when you have more than two possible outcomes, extending the basic if-else structure.

Syntax

if (condition1) {
    // Code executes if condition1 is true
} else if (condition2) {
    // Code executes if condition1 is false and condition2 is true
} else {
    // Code executes if all above conditions are false
}

Example Program

#include <iostream>
using namespace std;

int main() {

    int marks;
    cout << "Enter your marks: ";
    cin >> marks;

    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;
}

Output (example)

Enter your marks: 82
Grade: B

Key Points

  • The else if allows checking multiple conditions in sequence.
  • The first true condition is executed, and the rest are skipped.
  • An optional else block can handle all remaining cases.
  • Always order conditions from most specific to least specific to avoid logical errors.

Next Topic

After else if statements, you can learn about the Switch Statement for handling multiple discrete cases more efficiently.