bugl
bugl
HomeLearnPatternsPathsSearch
HomeLearnPatternsPathsSearch

Loading lesson path

Learn/C++/C++ Tutorial
C++•C++ Tutorial

C++ Nested If

Flash cards

Review the key moves

1/4
Core idea

What is the main idea behind C++ Nested If?

Lesson checks

Practice each idea before moving on

Short Mimo-style checks built from this lesson's code, terms, and sequence.

1Quick choice

Which statement best captures the main point of this lesson?

2Fill blank

Complete the missing token from the example code.

___ (condition1) {
3Order

Put the learning moves in the order that makes the concept easiest to apply.

In this example, we first check if x is greater than 10.
A nested if lets you check for a condition only if another condition is already true .
You can also place an if statement inside another if .

Nested If

You can also place an if statement inside another if . This is called a nested if statement.

A nested if lets you check for a condition only if another condition is already true .

Syntax

if (condition1) {
 // code to run if condition1 is true
 if (condition2) {
 // code to run if both condition1 and condition2 are true
 }
}

Example

In this example, we first check if x is greater than 10. If it is, we then check if y is greater than 20:

Example

int x = 15;
int y = 25;
if (x > 10) {
  cout << "x is greater than 10\n";
  // Nested if
  if (y > 20) {
    cout << "y is also greater than 20\n";
  }
}

Real-Life Example

Nested if statements are useful when you need to test multiple conditions that depend on each other. For example, checking if a person is old enough to vote, and if they are a citizen:

Example

int age = 20;
bool isCitizen = true;
if (age >= 18) {
  cout << "Old enough to vote.\n";
  if (isCitizen) {
    cout << "And you are a citizen, so you can vote!\n";
  } else {
  cout << "But you must be a citizen to vote.\n";
}
} else {
cout << "Not old enough to vote.\n";
}

Notes

  • You can nest as many if statements as you want, but avoid making the code too deep - it can become hard to read.
  • Nested if is often used together with else and else if for more complex decision making.

Previous

C++ Short Hand If Else

Next

C++ Logical Operators in Conditions