Nested if statement in C
A nested if–else means using an if–else statement inside another if or else block.
It is used when a decision depends on another decision.
Why Nested if–else Is Needed
- When one condition must be checked before another
- When decisions are hierarchical
- When multiple related conditions exist
In simple words:
First condition is checked, and only if it is satisfied, the next condition is checked.
Syntax of Nested if–else
python
1if (condition1) {
2 if (condition2) {
3 // code
4 } else {
5 // code
6 }
7} else {
8 // code
9}How It Works (Explanation)
- The outer
ifcondition is checked first - If it is true, the inner
if–elseis executed - If it is false, the outer
elseblock runs - Inner conditions are checked only when outer condition is true
Real-Life Example
Situation: Office Entry System
A person can enter the office:
- If they have an ID card
- If security clearance is approved → Entry allowed
- Else → Security check failed
- Else → ID not found
This is a perfect example of nested decision making.
Program Example (Nested if–else)
c
1#include <stdio.h>
2
3int main() {
4 int hasID = 1;
5 int securityClear = 0;
6
7 if (hasID == 1) {
8 if (securityClear == 1) {
9 printf("Entry Allowed");
10 } else {
11 printf("Security Check Failed");
12 }
13 } else {
14 printf("ID Not Found");
15 }
16
17 return 0;
18}