Nested conditionals
- C course
- Beginner
- Lesson 40/116
- 5 min
Learn to build complex logic with nested if and switch.
Nested if
You can put another if inside an if block. This creates nested conditions; for example first a broad category, then a sub-category.
int age = 25;
int has_ticket = 1;
if (age >= 18) {
if (has_ticket) {
printf("Allowed\n");
} else {
printf("Need ticket\n");
}
} else {
printf("Underage\n");
}Nested conditions are powerful but hurt readability as they deepen. Beyond three levels prefer && or a helper function.
if inside switch
You can also use if inside switch blocks. This is useful when each case needs extra conditional logic.
int role = 1;
int level = 5;
switch (role) {
case 1:
if (level >= 3) {
printf("Manager\n");
} else {
printf("Apprentice\n");
}
break;
default:
printf("Guest\n");
}Here role=1 and level=5 give the output Manager. Indentation at every level keeps the code readable.
Practice Entry check with nested if
Write a C program. Declare int age = 25; and int has_ticket = 0;. Write an outer if (age >= 18); inside it use if (has_ticket) to print printf("Allowed\n"); and else to print printf("Need ticket\n");. In the outer else print printf("Underage\n");. Put #include <stdio.h> at the top.
Starter code
#include <stdio.h>
int main(void) {
// Declare age and has_ticket, check with nested if
return 0;
}Sample solution
#include <stdio.h>
int main(void) {
int age = 25;
int has_ticket = 0;
if (age >= 18) {
if (has_ticket) {
printf("Allowed\n");
} else {
printf("Need ticket\n");
}
} else {
printf("Underage\n");
}
return 0;
}Expected output
Need ticket
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Complete the inner if
if (age >= 18) {
____ (has_ticket) {
printf("Allowed");
}
}
if (age >= 18) {
if (has_ticket) {
printf("Allowed");
}
}
Explanation: A second if check is done inside.
2 For age=25, has_ticket=0 what's the output?
if (age >= 18) {
if (has_ticket) printf("Allowed");
else printf("Need ticket");
} else printf("Underage");- Need ticket Correct answer
- Allowed
- Underage
- Empty output
Explanation: age is 18+ but no ticket; the inner else runs.
3 Match the nested structures
| Term | Meaning |
|---|---|
if inside if |
Tiered check |
if inside switch |
Sub-condition in a case |
&& operator |
Two conditions in one if |
else if |
Chain condition |