• When we have multiple options available or we need to take multiple decisions based on available condition, we can use another form of if statement called else…if ladder.
  • In else…if ladder each else is associated with another if statement.
  • Evaluation of condition starts from top to down.
  • If condition becomes true then the associated block with if statement is executed and rest of conditions are skipped.
  • If the condition becomes false then it will check for next condition in a sequential manner.
  • It repeats until all conditions are cheeked or a true condition is found.
  • If all condition available in else…if ladder evaluated to false then default else block will be executed.
  • It has the following syntax:

Syntax:

if (condition 1)
{
  // block 1
}
else if (codition 2)
{
  // block 2
}
else if(codition 3)
{
   // block 3
}
else
 {                   
    // default block
 }

Else If Ladder

  • else…if ladder provides multi way decision making when any one alternative is to be select among the available option.
  • The following block demonstrates the use of else if ladder.
#include<stdio.h>
#include<conio.h>
void main()
{
   int x, y, z, ch;
   clrscr();

   printf("\n1.Addition\n2.Subtraction\n3.Multiplication\4.Division\n");
   printf("\nEnter your choice :");
   scanf("%d",  &ch);
   
   printf("\nEnter X and Y :");
   scanf("%d %d", &x, &y);
 
   if (ch == 1)
   {
      z = x + y;
   }
   else if (ch == 2)
   {
      z = x - y;
   }
   else if(ch == 3)
   {
      z = x * y; 
   }
   else if(c == 4)
   {                   
    z = x/y ;
   }
  else
  {
    printf("\n Invalid choice! Please try again!");
  }
   printf("\n Answer is %.2f", z);
   getch();
}