if-else if-else Statement

An if statement can be followed by an optional else if…else statement, which is very useful to test various conditions using single if…else if statement.

When using if…else if..else statements, there are few points to keep in mind −

  1. An if can have zero or one else’s and it must come after any else if’s.

  2. An if can have zero to many else if’s and they must come before the else.

  3. Once an else if succeeds, none of the remaining else if’s or else’s will be tested.

Syntax

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
}

Flowchart Of if-else if-else Statement

if-else-if-flowchart

Program On if-else if-else Statement

if-else-if-program

Output

if-else-if-output

Nested if Statement

The nested if…else statement allows you to check for multiple test expressions and execute different codes for more than two conditions.

Syntax

if(testExpression 1) {

   /* Executes when the boolean expression 1 is true */
   if(testExpression 2) {
      /* Executes when the boolean expression 2 is true */
   }
}

Flowchart For nested if Statement

nested-if-flowchart

Program On nested if Statement

nested-if-program

Output

nested-if-output