Friday, 30 August 2013

Nested “if–else” Statement | C Programming Language Tutorial



Nested “if–else” Statement:

=> Using of one if-else statement in another if-else statement is called as nested if-else control statement.
=> When a series of decisions are involved, we may have to use more than one ifelse statement in nested form.
Syntax:
if ( Test Condition1)
{
if ( Test Condition2)
{
Statement -1;
}
else
{
Statement -2;
}
}
else
{
if ( Test Condition3)
{
Statement -3;
}
else
{
Statement -4;
}
} /* end of outer if-else */
=> If Test Condition-1 is true then enter into outer if block, and it checks Test Condition-2 if it is true then Statement-1 executed if it is false then else block executed i.e Statement-2.
=> If Test Condition -1 is false then it skips the outer if block and it goes to else block and Test Condition-3 checks if it is true then Statement-3 executed, else Statement-4 executed.

Example 1:
Program to select and print the largest of the three float numbers using nested “if-else” statements.
# include<stdio.h>
# include<conio.h>
main( )
{
float a,b,c;
printf(“Enter Three Values:”);
scanf(“%f%f%f ”, &a, &b, &c);
printf(“\n Largest Value is:”) ;
if(a>b)
{
if(a>c)
printf(“ %f ”, a);
else
printf(“ %f ”, c);
}
else
{
if (b>c)
printf(“ %f ”, b);
else
printf(“ %f ”, c);
}
getch( );
}

Output:
Run 1: Enter three values: 9.12 5.34 3.87
Largest Value is: 9.12
Run 2: Enter three values: 45.781 78.34 145.86
Largest Value is: 145.86
Run 3: Enter three values: 4.0 8.0 2.0
Largest Value is: 8.0

0 comments:

Post a Comment

 

C Programming Language Interview Questions and Answers Tutorial for beginners. Copyright 2013 All Rights Reserved