In C++, the else if
statement allows programs to evaluate multiple conditions sequentially. If the first condition is false, the program moves to the next condition. This ensures different outcomes based on varying conditions.
How the Else If Statement Works
When an if
condition fails, an else if
statement provides another chance to check for a different condition. If all conditions are false, the else
block executes.
Syntax
C++
x
if (condition1) {
// Runs if condition1 is true
} else if (condition2) {
// Runs if condition1 is false and condition2 is true
} else {
// Runs if condition1 and condition2 are both false
}
Example: Evaluating Speed Zones
The following program determines a message based on a vehicle’s speed.
C++
using namespace std;
int main() {
int speed = 90;
if (speed < 40) {
cout << "You're going too slow!";
} else if (speed < 100) {
cout << "You're cruising at a safe speed.";
} else {
cout << "Warning: Speed is too high!";
}
return 0;
}
Explanation of the Example:
speed = 90
- The first condition (
speed < 40
) is false, so it skips that block. - The
else if
condition (speed < 100
) is true, so"You're cruising at a safe speed."
gets printed. - If
speed
were 120, neither theif
norelse if
would be true, so theelse
block would execute.