How to Use The else if statement in C++ ?


The else if statement in C++ is used to test multiple conditions and execute different blocks of code based on the conditions. It is used in conjunction with the if statement and the else statement.

The syntax for the else if statement is as follows:

if (condition1) {
    // code to execute if condition1 is true
}
else if (condition2) {
    // code to execute if condition2 is true
}
else if (condition3) {
    // code to execute if condition3 is true
}
else {
    // code to execute if none of the conditions are true
}

Here's an example of how to use the else if statement in C++:

#include <iostream>

using namespace std;

int main() {
    int num;

    cout << "Enter a number: ";
    cin >> num;

    if (num > 0) {
        cout << "The number is positive." << endl;
    }
    else if (num < 0) {
        cout << "The number is negative." << endl;
    }
    else {
        cout << "The number is zero." << endl;
    }

    return 0;
}

In this example, the program prompts the user to enter a number. If the number is greater than 0, the program outputs "The number is positive." If the number is less than 0, the program outputs "The number is negative." If the number is equal to 0, the program outputs "The number is zero."



About the author

William Pham is the Admin and primary author of Howto-Code.com. With over 10 years of experience in programming. William Pham is fluent in several programming languages, including Python, PHP, JavaScript, Java, C++.