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
1
2if (condition1) {
3 if (condition2) {
4 // code
5 } else {
6 // code
7 }
8} else {
9 // code
10}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
2#include <stdio.h>
3
4int main() {
5 int hasID = 1;
6 int securityClear = 0;
7
8 if (hasID == 1) {
9 if (securityClear == 1) {
10 printf("Entry Allowed");
11 } else {
12 printf("Security Check Failed");
13 }
14 } else {
15 printf("ID Not Found");
16 }
17
18 return 0;
19}