Understanding the else if Statement in C++

The else if statement allows you to check multiple conditions sequentially. If the first condition is false, it checks the next one, and so on.

Syntax of the if...else if...else Statement

if (condition1) {
    // Code to execute if condition1 is true
} else if (condition2) {
    // Code to execute if condition2 is true
} else {
    // Code to execute if all conditions are false
}

Example: Using the else if Statement

#include <iostream>

int main() {
    int temperature = 30;
    if (temperature > 35) {
        std::cout << "It's very hot." << std::endl;
    } else if (temperature > 25) {
        std::cout << "It's warm." << std::endl;
    } else {
        std::cout << "It's cool." << std::endl;
    }
    return 0;
}

Explanation: The program checks the temperature and prints a message accordingly. Since the temperature is 30, it prints "It's warm."

Key Takeaways

  • The else if allows for multiple conditional checks.
  • Only the first true condition's block is executed.
  • Useful for handling multiple mutually exclusive conditions.