Nested if statement

To check on condition within another we use nested if statement. The else clause is always associated with the closest matched if.

The syntax is :-

if  ( expression)
{

if ( expression)
{

if ( expression)
…. you can put N number of  if  ( expression )….
{

statement 1;

}
else
{

statement 2;

}

}
else
{

statement 3;

}

}

else
{

statement 4;

}

Example:-
Write a C program to check given number is divisible by 2,3 and 4 or not

#include<stdio.h>
int main()
{

int num;scanf(“%d”,&num);

if (num%2 == 0)
{

if (num%3 == 0)
{

if (num%4 == 0)
{

printf(“Num = %d is divisible by 2,3 and 4\n”,num);

}
else
{

printf(“Num = %d is not divisible by 4\n”,num);

}

}
else
{

printf(“Num = %d is not divisible by 3\n”,num);

}

}
else
{

printf(“Num = %d is not divisible by 2\n”,num);

}
return 0;

}

Explanation :-
Case 1 : Suppose you have entered num = 12,  The value is successfully validate in each if statement one by one, The output will be :-
$ ./a.out
12
Num = 12 is divisible by 2,3 and 4

Case 1 : Suppose you have entered num = 10,  The value is successfully validate in first if statement, but fails in second if statement, so else part of second if will execute, the output will be :-
$  ./a.out
10
Num = 10 is not divisible by 3

 

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.