AP CSP
AP Computer Science Principles / All lessons / Big Idea 3: Algorithms and Programming
3Big Idea 3: Algorithms and Programming
AP CSP topic 3.7

Nested Conditionals

A nested conditional is an IF statement inside another IF statement. The inner condition is checked only when the outer one leads there. Nesting lets programs handle several cases, like assigning letter grades or deciding ticket prices by age and day. Order matters: checking the most specific case first often avoids logic errors.

Nested Conditionals vocabulary

  • Nested conditional: A conditional statement placed inside another conditional.
  • Branch: One possible path through a conditional.
  • Trace: Following code step by step by hand to see what it does.
  • Logic error: A mistake that makes code run but give the wrong result.

AP-style practice questions

Try each one, then open the answer. To save your progress, take this quiz in the interactive course.

Skill: Code Analysis
IF (score ≥ 90)
{
   grade ← "A"
}
ELSE
{
   IF (score ≥ 80)
   {
      grade ← "B"
   }
   ELSE
   {
      grade ← "C"
   }
}

1. What is the value of grade when score is 85?

  1. (A) "A"
  2. (B) "B"
  3. (C) "C"
  4. (D) grade is not set
Show answer

(B) "B" 85 ≥ 90 is false, so the inner IF runs, and 85 ≥ 80 is true.

Skill: Code Analysis
IF (score ≥ 60)
{
   result ← "Pass"
}
ELSE
{
   IF (score ≥ 90)
   {
      result ← "Honors"
   }
}

2. A programmer wants scores of 90 or more to get "Honors". Why does this code never set "Honors"?

  1. (A) Scores of 90 or more already match the first condition, so the inner IF is never reached for them
  2. (B) The ELSE block always runs
  3. (C) MOD should be used instead of ≥
  4. (D) A score cannot be greater than 60
Show answer

(A) Scores of 90 or more already match the first condition, so the inner IF is never reached for them Any score ≥ 90 is also ≥ 60, so it takes the first branch. Check the more specific case first.

Skill: Code Analysis
day ← "Sat"
age ← 10
IF (day = "Sat")
{
   IF (age < 12)
   {
      price ← 5
   }
   ELSE
   {
      price ← 8
   }
}
ELSE
{
   price ← 10
}

3. What is the value of price?

  1. (A) 5
  2. (B) 8
  3. (C) 10
  4. (D) price is not set
Show answer

(A) 5 It is Saturday and age 10 is under 12, so price is 5.

Skill: Algorithms and Program Development

4. Which of the following is a reason to use a nested conditional?

  1. (A) To repeat a step many times
  2. (B) To check a second condition only after a first condition has been decided
  3. (C) To store many values in one variable
  4. (D) To make a program run in parallel
Show answer

(B) To check a second condition only after a first condition has been decided Nesting lets the program test an inner condition only on certain paths.

Open 3.7 in the interactive course