C++ Else Statement

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.

Tutorials dojo strip



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++




Example: Using else in a Program

The program below determines whether daylight or nighttime messages should be displayed:

C++

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).

Tutorials dojo strip