Table of Contents
A nested if statement is an if statement placed inside another if statement. It allows a program to evaluate a second condition only when an outer condition has already been satisfied.
Nested conditions are useful when a decision depends on multiple levels of related conditions.
Source Code #
#include <iostream>
int main()
{
int age = 20;
bool has_license = true;
if (age >= 18)
{
if (has_license)
{
std::cout << "Eligible to drive.\n";
}
}
return 0;
}
Output #
Eligible to drive.
Explanation #
- The outer
ifstatement checks whetherageis at least18. - The inner
ifstatement is located inside the block of the outerifstatement. - The inner condition is evaluated only when the outer condition evaluates to
true. has_licenseis checked only after the age requirement has been satisfied.- Both conditions must evaluate to
truefor"Eligible to drive."to be displayed. - Nested
ifstatements can contain furtherifstatements when additional levels of decision-making are required. - Curly braces define the scope of each
ifblock. return 0;terminates the program successfully.