C++ if-else ladder

  • if-else if- else ladder is very useful in order to check several conditions using single if-else if statement.
  • In this type of statement 'if' is followed by one or more elseIf statements and finally end with a else statement.
  • Here is a syntax of if-else if- else ladder:
  • Syntax

    if(condition1)

    {

    Statements;

    }

    else if (condition2)

    {

    Statements;

    }

    else

    {

    Statements;

    }
  • In the above syntax if condition 1 is true then statements present inside the if block will be executed and if the condition1 is false then compiler will check the condition2 if it is true then statements present inside the else if block will be executed and if the condition2 is false then finally statements present inside the else block will be executed. You can understand this concept more clearly with the help of following diagram:
  • decision-making While using if- else if- else ladder we have to remember these points:
  • Once an else if succeeds, none of the remaining else if's or else's will be tested.
  • if statement can be followed by one and more than one else if statements.
  • Here is an example of if-else statement as follows:

Example

#include<iostream.h>

#include<conio.h>

int main()

{

int a,b;

cout<<"\n Enter the value of a and b:";

cin>>a>>b;

if(a>b)

{

cout<<"value of a is greater than b";

}

else if(a<b)

{

cout<<"value of a is less than b";

}

else

{

cout<<"value of a and b are equal";

}

getch();

return 0;

}

Output

The output of the above program is as follows:

Enter the value of a and b: 2

4

value of a is less than b

In the above example we have declared two variables a and b. here we have used cin function to read the input from the console. When we give the input then first value is assigned to a, and 2nd value is assigned to b. after that we have used if-else leader statement. Inside this we have checked that if the both variable values are same then if block will be executed and if it is false then else-if condition will be checked otherwise else part will be executed. In this example else-if part will execute because the condition is true. So this part will be executed.