if elseif else ladder in c

If elseif else ladder in c, allows to check more than one condition or expression, if any of given condition becomes true, then it executes the related block set of statements, if not, then it executes statements of else block.

  1. If always be the first block.
  2. elseif always comes after if block.
  3. There can be more than one elseif blocks, but there should be at least one elseif block.
  4. else block always comes after elseif and must be the last block.
  5. else is always optional.

Syntax

if(expression)
{
  //set of statements
}
else if(expression)
{
  //set of statements
}
else if(expression)
{
  //set of statements
}
else
{
  //set of statements
}

Example

#include<stdio.h>

void main()
{
    int speed = 30;
    if(speed <= 30)
    {
       printf("Safe speed");
    }
    else if(speed <= 50)
    {
       printf("Above speed safety limit");
    }
    else if(speed <= 120)
    {
       printf("Danger, Slow down");
    }
    else
    {
       printf("Car is not moving");
    }
}

Explanation

  1. In above example, variable speed is declared and initialized with value 30.
  2. If (speed <= 30), it returns true, then if block statements gets executed.
  3. If it returns false, then it checks the next else if(speed <= 50), If it returns true, then the related statements executes.
  4. Similarly it checks until any if or elseif condition returns true. If any of them not return true, then else block statements executes.