• Home
  • 4.3 Nested if Statement

4.3 Nested if Statement

View Categories

4.3 Nested if Statement

< 1 min read

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 if statement checks whether age is at least 18.
  • The inner if statement is located inside the block of the outer if statement.
  • The inner condition is evaluated only when the outer condition evaluates to true.
  • has_license is checked only after the age requirement has been satisfied.
  • Both conditions must evaluate to true for "Eligible to drive." to be displayed.
  • Nested if statements can contain further if statements when additional levels of decision-making are required.
  • Curly braces define the scope of each if block.
  • return 0; terminates the program successfully.

Powered by BetterDocs

Leave a Reply

Your email address will not be published. Required fields are marked *