Header Ads Widget

Nested if

When any if statement is written under another if statement, this cluster is called a nested if.
if(Test Exp1)
{
     if(Test Exp2)
         Statement A;
     else
         Statement B;
}
else
      Statement C;

An else always associates itself with the closest if. Nesting of  if-else statement is also written as :

if(Test Exp1)
{
     if(Test Exp2)
         Statement A;
     else
         Statement B;
}
else
{
       if(Test Exp3)
         Statement C;
     else
         Statement D;
}

Example : Program to find the largest among three integers.

#include <stdio.h>
int main( )
{
int x,y,z;
printf("Enter three integers :");
scanf("%d %d  %d",&x,&y,&z);
if(x > y)
     if(x > z)
        printf("Largest integer = %d",x);
     else
        printf("Largest integer = %d",z);
else
     if(y > z)
        printf("Largest integer = %d",y);
     else
        printf("Largest integer = %d",z);
return 0;
}

Output :
Enter three integers :44
48
12
Largest integer = 48


Post a Comment

0 Comments