Nested ‘if’ Statement

Estudies4you

Nested ‘if’ statement
When an ‘if’ statement has another ‘if’ statement as one of its possible processing branches, these ‘if’ statements are said to be nested.

Syntax:
if(boolean_expression 1)
{
//Executes when the Boolean expression 1 is true
if(Boolean_expression 2)
{
// executes when the Boolean expression 2 is true
}
}

Example:
Sample C program for nested if statement
#include<stdio.h>
int main(void)
{
int i;       //the integer value is declared as ‘i’.
printf(“enter either 1(for Birthday) or 2(for Wedding Day)”);       //Text displayed asking user to enter either 1 or 2
scanf(“%d”,&i); //the integer i is scanned
if(i==1) //if ‘i' is equal to 1 then the statement, we wish you a happy birthday is displayed.
printf(“we wish you a happy birthday”);
else
{
if(i==2) //if i is equal to 2 then the next statement will be displayed.
printf(“we wish you a happy wedding day”);
else
printf(“Have a nice day anyway”);
}
return 0;
}
OUTPUT
Enter either 1 or 2
3
Have a nice day anyway

To Top