Nested if else Statement in C Language

 

Nested if  else Statement in C Language



What is Nested if - else Statement in C Programming:

When numerous if else statements inside the if else statement is used it is called nesting process. The second if else statement used is called nested inside the first if else statement. The nesting statement is used in the situation where more than one conditions has to be checked and then make the decisions. C compiler allows to programmer to use more than one of else statement for decision making.

Syntax for nested if else statement:


if(test condition) //first if condition true

{

if(test Condition) // if second condition true

{

//statement

}

else // if second condition does not true

{

//statement

}

}// first if block close

else // if the first condition does not true

{

//statement

if(test condition3) // if third condition true

{

//statement

}

else // if third condition does not true

{

//statement

}

}


In the above syntax of nested if else statement, two if else statements are used within the if else statement and it is called nested if else statements. If the test condition written in first if statement become true then compiler will go to the second if statement. If second if condition is true then compiler will execute the related statement in second if block. If second if condition becomes false then compiler will execute the first else statement.

If the first test condition becomes false then compiler will skip the first if block and it will jump to the second else statement i.e. else block of if else statement and execute the related statement. In the else the third if condition is used if it becomes true then the related statement will execute otherwise the nested else statement written in main else statement execute and display the result.

Following example shows the use of nested if else statement in C Language.


/*********************************************************
Program to find calculated sum is even or odd using nested if else statement
***************************************************************/
#include<stdio.h>
#include<conio.h>
void main()
{
int n1,n2,n3;
int sum;

clrscr();
printf("Enter three numbers\n");
scanf("%d%d%d",&n1,&n2,&n3);
sum=n1+n2+n3;
printf("The sum is:\t%d\n",sum);
if(sum%2==0)
{
printf("Calculated sum %d is even\n",sum);

if(sum%4==0)
{
printf("Calculated sum: %d is divisible by 4\n",sum);
}

else
{
printf("Calculated sum:%d is not divisible by 4\n",sum);
}
}
else{
printf("Calculated sum: %d is odd number\n",sum);
if(sum%3==0)
{
printf("The calculated sum: %d is divisible by 3\n", sum);
}
else
{
printf("The calculated sum:%d is not divisible by 3\n",sum);

}
}
printf("End of program");
}


Enter three numbers

12

13

14

The sum is: 39

Calculated sum: 39 is odd number

The calculated sum: 39 is divisible by 3

End of program

टिप्पणी पोस्ट करा

0 टिप्पण्या