CodeBlanks Logo Icon CodeBlanks

Nested conditionals

Learn to build complex logic with nested if and switch.

Nested if

When a condition is meaningful only if another condition is also true, you use a nested if. You write a second if inside the outer if's block; the inner condition is then evaluated only when the outer one is true.

For example: if (age >= 18) { if (hasLicense) { std::cout << "Can drive"; } }. Here hasLicense is checked only when age is 18 or above. Nested if can hurt readability; combining with logical operators is a good alternative.

if inside switch

switch and if can be used together. When you want a case to produce different output based on another condition, you place an if inside the case body. This combines a categorical choice with a sub-condition.

For example, in switch (role) { case 1: if (active) { ... } break; } special code runs only when role is 1 and active is true. Indentation and short blocks help keep nested structures readable.

Practice Compute the letter grade

The score variable is set to 85. With if (score >= 90) set grade to "A", with else if (score >= 80) to "B", and with else to "C"; then print it with std::cout. The output must be B.

Starter code

main.cpp
#include <iostream>
#include <string>

int main() {
    int score = 85;
    std::string grade;
    // Assign the letter grade and print it
    return 0;
}

Sample solution

main.cpp
#include <iostream>
#include <string>

int main() {
    int score = 85;
    std::string grade;
    if (score >= 90) {
        grade = "A";
    } else if (score >= 80) {
        grade = "B";
    } else {
        grade = "C";
    }
    std::cout << grade << std::endl;
    return 0;
}

Expected output

B

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 In a nested if, what happens when the outer condition is false?

main.cpp
if (outer) {
  if (inner) { ... }
}
  • The inner condition is skipped Correct answer
  • The inner condition still runs
  • The program crashes
  • An infinite loop forms

Explanation: When the outer condition is false none of the inner block runs.

2 Write the nested if condition

Question
bool hasLicense = true;
if (age >= 18) {
    if (____) { std::cout << "Can drive"; }
}
Answer
bool hasLicense = true;
if (age >= 18) {
    if (hasLicense) { std::cout << "Can drive"; }
}

Explanation: hasLicense is the right inner condition.

3 Match each construct to its scenario

Term Meaning
if (a) { if (b) { ... } } Both conditions needed
switch (x) { case 1: if (y) { ... } } Sub-condition in a case
if (a) { ... } else { ... } Two-way choice
switch (x) { default: ... } Catch-all case

All lessons in Beginner