Nested if

The if and if ... else statements can be nested to accomplish a more complex decision making logic. Nested if statements are formed by writing if and if ... else statements inside other if and if ... else statements.

Here is an example

if (condition1) {
	if (condition2) {
  		statement_block1;
	}
	else {
 		statement_block2;
	}
	statement3;
}
else {
     	if (condition3) statement4;
}

The flowchart of the above nested if statements is as below

Nested if flowchart

Example

Below is a program that finds the smallest of three numbers.

#include <stdio.h>

int main() 
{
int a,b,c;

printf("Enter three numbers \\n");
scanf("%d%d%d", &a,&b,&c);

if (a < b) {
	if (a < c) {
		printf("%d is the smallest",a);
	}
	else {
		printf("%d  is the smallest",c);
	}
}
else {
	if (b < c) printf("%d  is the smallest",b);
	else printf("%d  is the smallest",c);
}
return 0;
}
Last Updated: 06-June-2013


Post a comment

Name

Your Comment

Email (We dont publish it)

Comments

Nothing yet..be the first to share wisdom.