In C++, the else statement works alongside if to provide an alternative course of action when a condition is false. It ensures that a program reacts appropriately when certain conditions aren’t met.
How the else Statement Works
An if
statement checks a condition—if true, a specific block of code runs. If false, the program moves to the else
block, executing that instead.
Syntax
C++
x
if (condition) {
// Code executes only if condition is true
} else {
// Code executes if condition is false
}
Example: Using else in a Program
The program below determines whether daylight or nighttime messages should be displayed:
C++
using namespace std;
int main() {
int ridingTime = 20;
if (ridingTime < 18) {
cout << "Enjoy your daytime ride!";
} else {
cout << "Ride safe—it's getting late!";
}
return 0;
}
Explanation:
ridingTime
is set to 20.- The
if
condition checks if it’s less than 18. - Since 20 is greater than 18, the condition is false, so the program moves to the else block.
- It prints: “Ride safe—it’s getting late!”
If ridingTime
had been 10, it would have displayed “Enjoy your daytime ride!” instead.
Why Use else?
The else
statement ensures that something always happens, even when a condition fails.
Common use cases include:
- Displaying messages based on time or weather.
- Checking vehicle performance (e.g., low fuel warnings).
- Validating user input (e.g., confirming passwords).