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.
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?
- (A) "A"
- (B) "B"
- (C) "C"
- (D) grade is not set
Show answer
(B) "B" 85 ≥ 90 is false, so the inner IF runs, and 85 ≥ 80 is true.
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"?
- (A) Scores of 90 or more already match the first condition, so the inner IF is never reached for them
- (B) The ELSE block always runs
- (C) MOD should be used instead of ≥
- (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.
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?
- (A) 5
- (B) 8
- (C) 10
- (D) price is not set
Show answer
(A) 5 It is Saturday and age 10 is under 12, so price is 5.
4. Which of the following is a reason to use a nested conditional?
- (A) To repeat a step many times
- (B) To check a second condition only after a first condition has been decided
- (C) To store many values in one variable
- (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.