A nested if in C is an if statement that is the target of another if statement. Nested if statements means an if statement inside another if statement. Yes, both C and C++ allows us to nested if statements within if statements, i.e, we can place an if statement inside another if statement.
Simple if and if...else...if statements provide a great support to control programs flow. Simple if is single condition based task i.e. "if some condition is true, then do the task". In contrast if...else...if statement provides multiple condition checks i.e. "if some condition is true, then do some task. If the condition is false, then check some other condition and do some task. If all conditions fails, then do some default task."
Consider a situation, where you want to execute a statement based on multiple levels of condition check. For example - At airport there are multi-levels of checking before boarding. First you go for basic security check, then ticket check. If you have valid ticket, then you go for passport check. If you have valid passport, then again you will go for security check. If all these steps are completed successfully, then only you can board otherwise actions are taken by the authority.
Nested if...else statements has ability to control program flow based on multiple levels of condition.
Syntax of nested if...else statement
if (boolean_expression_1)
{
if(nested_expression_1)
{
// If boolean_expression_1 and
// nested_expression_1 both are true
}
else
{
// If boolean_expression_1 is true
// but nested_expression_1 is false
}
// If boolean_expression_1 is true
}
else
{
if(nested_expression_2)
{
// If boolean_expression_1 is false
// but nested_expression_2 is true
}
else
{
// If both boolean_expression_1 and
// nested_expression_2 is false
}
// If boolean_expression_1 is false
}
If the body of an if...else statement has only one statement, you do not need to use brackets {}
For example, this code
if (a > b) {
print("Hello");
}
print("Hi");
is equivalent to
if (a > b)
print("Hello");
print("Hi");
Flowchart of nested if...else statement
Example program of nested if...else statement
/**
* C program to find maximum between three numbers
*/
#include <stdio.h>
int main()
{
/* Declare three integer variables */
int num1, num2, num3;
/* Input three numbers from user */
printf("Enter three numbers: ");
scanf("%d%d%d", &num1, &num2, &num3);
if(num1 > num2)
{
if(num1 > num3)
{
/* If num1>num2 and num1>num3 */
printf("Num1 is max.");
}
else
{
/* If num1>num2 but num1<num3 */
printf("Num3 is max.");
}
}
else
{
if(num2 > num3)
{
/* If num1<num2 and num2>num3 */
printf("Num2 is max.");
}
else
{
/* If num1<num2 and num2<num3 */
printf("Num3 is max.");
}
}
return 0;
}
Output of the above program
Enter three numbers: 10
20
30
Num3 is max.
Let us now understand the working flow of above program.