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) statement 1;
} statement 2; }
} 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);
} printf(“Num = %d is not divisible by 4\n”,num); }
} printf(“Num = %d is not divisible by 3\n”,num); }
} printf(“Num = %d is not divisible by 2\n”,num);
} } Explanation :- 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 :- |