C++ else..if ladder



In the previous chapters we have seen different tutorials on if statement and if-else statement.

When we need to list multiple else if…else statement blocks. We can check the various conditions using the following syntax –

Syntax : C++ Else if ladder

if(boolean_expression 1)
{
   // When expression 1 is true
}
else if( boolean_expression 2)
{
   // When expression 2 is true
}
else if( boolean_expression 3)
{
   // When expression 3 is true
}
else 
{
   // When none of expression is true
}

When the first Boolean condition becomes true then first block gets executed.

When first condition becomes false then second block is checked against the condition. If second condition becomes true then second block gets executed.

Example : Else if ladder

#include <iostream>
using namespace std;
 
int main ()
{
   // declare local variable
   int marks = 55;
 
   // check the boolean condition
   if( marks >= 80 )
   {
       // if 1st condition is true
       cout << "U are 1st class !!" << endl;
   }
   else if( marks >= 60 && marks < 80)
   {
       // if 2nd condition is false
       cout << "U are 2nd class !!" << endl;
   }
   else if( marks >= 40 && marks < 60)
   {
       // if 3rd condition is false
       cout << "U are 3rd class !!" << endl;
   }
   else 
   {
       // none of condition is true
       cout << "U are fail !!" << endl;
   }
 
   return 0;
}

Output :

U are 3rd class !!

Explanation :

  1. Firstly condition 1 specified in the if statement is checked. In this case the condition becomes false so it will check the 2nd condition in the else if block.
  2. Now 2nd block condition also evaluates to be false then again the 2nd block will be skipped and 3rd block condition is checked.
  3. In the above example the condition specified in the 3rd block evaluates to be true so the third block gets executed.

Flowchart diagram :

Else if ladder

Some rules of using else if ladder in C++ :

Keep some important things in mind –

  1. if block can have zero or one else block and it must come after else-if blocks.
  2. if block can have zero to many else-if blocks and they must come before the else.
  3. After the execution of any else-if block none of the remaining else-if block condition is checked.