C Nested Conditions
In this page:
What is a Nested Condition?
A nested condition is an if statement placed inside the body of another if statement, and the inner condition is only evaluated at all once the outer condition has already been satisfied.
Example: What is a Nested Condition?
#include <stdio.h>
int main() {
int age = 25;
if (age >= 18) {
if (age < 65) {
printf("Working age");
}
}
return 0;
}
Login to try C/C++/Java/PHP code in the editor
Basic Nested if
In a basic nested if, the outer if statement's block contains a complete inner if statement, so reaching the innermost code requires every enclosing condition to be true.
Example: Basic Nested if
#include <stdio.h>
int main() {
int n = 10;
if (n > 0) {
if (n % 2 == 0) {
printf("Positive even");
}
}
return 0;
}
Login to try C/C++/Java/PHP code in the editor
Nested if-else
An else branch can itself contain a complete if-else statement, letting nested conditions distinguish between more than two outcomes, such as separating three different age categories.
Example: Nested if-else
#include <stdio.h>
int main() {
int age = 30;
if (age < 13) {
printf("Child");
} else {
if (age < 20) {
printf("Teen");
} else {
printf("Adult");
}
}
return 0;
}
Login to try C/C++/Java/PHP code in the editor
Multiple Levels of Nesting
Conditions can be nested several levels deep to check increasingly specific combinations of criteria, though very deep nesting tends to make code significantly harder to read and maintain.
Example: Multiple Levels of Nesting
#include <stdio.h>
int main() {
int a = 5;
if (a > 0) {
if (a < 10) {
if (a % 2 != 0) {
printf("Positive, single-digit, odd");
}
}
}
return 0;
}
Login to try C/C++/Java/PHP code in the editor
Nested Conditions vs Logical Operators
A nested if achieves the same result as combining conditions with the logical AND operator (&&) in a single if statement, and the logical-operator version is often considered more concise and readable for simple combined checks.
Example: Nested Conditions vs Logical Operators
#include <stdio.h>
int main() {
int a = 5;
if (a > 0) {
if (a < 10) {
printf("Nested version");
}
}
if (a > 0 && a < 10) {
printf("Logical operator version");
}
return 0;
}
Login to try C/C++/Java/PHP code in the editor
Chapter Quiz — Complete all 11 topics to unlock
0/11 topics done
Complete these topics first: