Definition: A nested if statement is an if statement placed inside another if statement. It is used when a second condition needs to be checked only after the first condition is true.
Definition: A nested if statement is an if statement placed inside another if statement. It is used when a second condition needs to be checked only after the first condition is true.
if (condition1)
{
if (condition2)
{
// statements
}
}
In a nested if, one condition is placed inside another condition. The inner condition is checked only when the outer condition is true.
#include <stdio.h>
int main()
{
int marks = 80;
if (marks >= 40)
{
if (marks >= 75)
{
printf("Student passed with distinction.");
}
}
return 0;
}
Student passed with distinction.
Nested if statements can be used when more than one condition must be checked step by step.
#include <stdio.h>
int main()
{
int a, b, c, largest;
printf("Enter three numbers: ");
scanf("%d %d %d", &a, &b, &c);
if (a > b)
{
if (a > c)
largest = a;
else
largest = c;
}
else
{
if (b > c)
largest = b;
else
largest = c;
}
printf("Largest number = %d", largest);
return 0;
}
Enter three numbers: 25 40 15 Largest number = 40
| Nested if | if-else |
|---|---|
| An if statement is placed inside another if statement. | Provides two alternative paths based on a condition. |
| Useful for dependent or step-by-step conditions. | Useful when one of two alternatives must be selected. |
| Inner condition depends on the outer condition. | The else block executes when the if condition is false. |
Nested if → Outer condition → Inner condition → Statement