C Nested If
Sometimes a decision depends on another decision. You can place an if statement inside another if statement to handle these layered situations. This is called a nested if, and it lets you check a second condition only after the first one has passed.
What is a nested if?
A nested if is simply an if (or if...else) placed inside the body of another if. The inner condition is only tested when the outer condition is true. Think of it like a locked door behind another locked door: you must open the first before you even see the second.
Checking a second condition
#include <stdio.h>
int main() {
int age = 20;
int hasTicket = 1;
if (age >= 18) {
if (hasTicket) {
printf("You may enter the show.\n");
} else {
printf("You need a ticket.\n");
}
}
return 0;
}Nested if with else branches
Each level of a nested if can have its own else, so you can respond to every combination of conditions. Indentation is your friend here: line up each block so you can see which else belongs to which if.
Login example
#include <stdio.h>
int main() {
int userFound = 1;
int passwordOk = 0;
if (userFound) {
if (passwordOk) {
printf("Welcome back!\n");
} else {
printf("Wrong password.\n");
}
} else {
printf("No such user.\n");
}
return 0;
}- The inner if is only reached when the outer condition is true.
- Use clear indentation so the structure is easy to read.
- Too many nested levels get hard to follow; sometimes logical operators like && are cleaner.
The same logic without nesting
#include <stdio.h>
int main() {
int age = 20;
int hasTicket = 1;
if (age >= 18 && hasTicket) {
printf("You may enter the show.\n");
}
return 0;
}