Ads block

Banner 728x90px

Nested if statement

Nested if statement is the next step of if-else statement. The nested if statement provides the facility to use a conditional if statement inside the another conditional if statement.

if(condition 1)
{
  if(condition 2)
   {
     // statements to be executed
      ......
   }
}
else
{
 //statements to be executed if condition 1 is false
}

Let's see an appropriate example of nested if statement.

//Program to check a candidate is eligible to get job or not.
#include<stdio.h>
void main()
{
  char ch;
  int age;
  printf("Enter your gender: ");
  scanf("%c",&ch);
  if(ch=='m' || ch=='M')
   {
     printf("Enter your age: ");
     scanf("%d",&age);
     if(age>=18)
        printf("Congrats! you got it.");
     else
        printf("Sorry! you are under 18.");
   }
  else
   printf("This is not for you.");
}

16
Sorry! you are not eligible
25
Congrats! you are eligible



if else-if ladder statement

The if else-if statement is used in that situation, when we want to execute different block code in different conditions. In this statement, there can be multiple block of code defined in the else-if statement and one block of code defined in the if statement.

The process starts by the checking of if block condition. If it is not true, then it will check the condition of else-if statement. If none of these condition is true, then in that situation else block code will be execute.

Here is the syntax of if else-if statement.

if(condition 1)
 {
  //to be executed if condition 1 is true
 }
else if(condition 2)
 {
  //to be executed if condition 2 is true.
 }
else if(condition 3)
 {
  //to be executed if condition 3 is true.
 }
else
  {
   //to be executed if all the above conditions are false.
  }