Understanding the else Statement in C++

The else statement is used with an if statement to execute a block of code when the condition is false.

Syntax of the if...else Statement

if (condition) {
    // Code to execute if condition is true
} else {
    // Code to execute if condition is false
}

Example: Using the if...else Statement

#include <iostream>

int main() {
    int age = 16;
    if (age >= 18) {
        std::cout << "You are eligible to vote." << std::endl;
    } else {
        std::cout << "You are not eligible to vote." << std::endl;
    }
    return 0;
}

Explanation: Since age is less than 18, the code inside the else block is executed.

Key Takeaways

  • The else block executes when the if condition is false.
  • Provides an alternative path of execution.
  • Useful for handling two mutually exclusive scenarios.