Controlling Program Flow: Introducing else Statements

What is it?

The else statement is a conditional statement used along with the if statement. It helps to execute a block of code when the condition specified in the if statement evaluates to false. If the specified condition evaluates to true, the block of code associated with the if statement is executed, and the block associated with the else statement is skipped.


Syntax

The basic syntax of using the if-else statement is as follows:

if(condition)
{
    // block of code to be executed when the condition is true
}
else
{
    // block of code to be executed when the condition is false
}

Where,

  • condition is an expression that is evaluated in a boolean context.



How to use it

To use the else statement, follow the below steps:

  1. Define an if statement that checks for a particular condition.
  2. If the condition evaluates to true, then the block of code beneath the if statement is executed.
  3. If the condition evaluates to false, then the block of code beneath the else statement is executed.



Program code snippet example

#include <iostream>

using namespace std;

int main()
{
    int age;

    cout << "Enter your age: ";
    cin >> age;

    if(age >= 18)
    {
        cout << "You are eligible to vote." << endl;
    }
    else
    {
        cout << "You are not eligible to vote." << endl;
    }

    return 0;
}

Output:

Enter your age: 20
You are eligible to vote.




Combine the if statements into a single if & else statement.