C++ Nested if...else

Share:
The if...else statement executes two different codes depending upon whether the test expression is true or false. Sometimes, a choice has to be made from more than 2 possibilities.
The nested if...else statement allows you to check for multiple test expressions and execute different codes for more than two conditions.

Syntax of Nested if...else

if (testExpression1) 
{
   // statements to be executed if testExpression1 is true
}
else if(testExpression2) 
{
   // statements to be executed if testExpression1 is false and testExpression2 is true
}
else if (testExpression 3) 
{
   // statements to be executed if testExpression1 and testExpression2 is false and testExpression3 is true
}
.
.
else 
{
   // statements to be executed if all test expressions are false
}

Example 3: C++ Nested if...else

// Program to check whether an integer is positive, negative or zero

#include <iostream>
using namespace std;

int main() 
{
    int number;
    cout << "Enter an integer: ";
    cin >> number;

    if ( number > 0)
    {
        cout << "You entered a positive integer: " << number << endl;
    }
    else if (number < 0)
    {
        cout<<"You entered a negative integer: " << number << endl;
    }
    else
    {
        cout << "You entered 0." << endl;
    }

    cout << "This line is always printed.";
    return 0;
}
Output
Enter an integer: 0
You entered 0.
This line is always printed.