What is Nested if Statement in C++?
The nested if statement means using an if statement inside another if statement. It is used when we need to check multiple conditions step by step.
In this, the inner if statement executes only when the outer condition is true.
Syntax of Nested if Statement:
if (condition1) {
if (condition2) {
// code if both conditions are true
} else {
// code if condition1 is true but condition2 is false
}
} else {
// code if condition1 is false
}
Explanation:
- First, condition1 is checked.
- If it is true, then condition2 is checked.
- If both are true, inner if block executes.
- If condition2 is false, inner else block executes.
- If condition1 is false, outer else block executes.
Example 1:
#include <iostream>
using namespace std;
int main() {
int marks = 75;
if (marks >= 40) {
if (marks >= 75) {
cout << "Passed with Distinction";
} else {
cout << "Passed";
}
} else {
cout << "Failed";
}
return 0;
}
Output:
Passed with Distinction
Explanation:
- First, marks >= 40 is checked → true.
- Then, marks >= 75 is checked → true.
- So, inner if block executes → "Passed with Distinction".
Example 2:
#include <iostream>
using namespace std;
int main() {
int age = 20;
bool hasLicense = true;
if (age >= 18) {
if (hasLicense) {
cout << "You can drive";
} else {
cout << "You need a driving license";
}
} else {
cout << "You are underage";
}
return 0;
}
Output:
You can drive
Explanation:
- First, age >= 18 is checked → true.
- Then, hasLicense is checked → true.
- Both conditions are true, so "You can drive" is printed.
Summary:
- Nested if means an if inside another if.
- It is used to check conditions step by step.
- Inner condition runs only if outer condition is true.
- It helps in writing detailed decision logic.
- Nested if is used for multiple condition checking.
- Too many nested ifs can make code complex.