AP CSP Day 61: Nested Conditionals with Compound Boolean Logic | Cycle 3
Share
A nested conditional places one IF statement inside another, creating a decision tree where the inner condition is only evaluated when the outer condition is true. Compound Boolean expressions use AND and OR to combine conditions into a single test. Tracing nested conditionals with compound operators requires careful attention to short-circuit evaluation and the order in which branches are checked.
Study the Concept First (Optional) Click to expand ▼
Nested Conditionals with AND/OR
Evaluation Order
When an IF is nested inside another IF, the outer condition must be true before the inner condition is even checked. If the outer condition is false, the entire inner block is skipped regardless of the inner condition.
Short-Circuit with AND
In an expression like (p AND q), if p is false, q is never evaluated because the result must be false. This means side effects inside q would not occur.
Practice Question
Consider the following code segment.
IF (x > 10)
{
IF (x < 20 AND y > 5)
{
DISPLAY("alpha")
}
ELSE
{
DISPLAY("beta")
}
}
ELSE
{
IF (y > 5)
{
DISPLAY("gamma")
}
ELSE
{
DISPLAY("delta")
}
}What is displayed when x ← 25 and y ← 8?
With x ← 25, the outer condition (x > 10) is true, so we enter the first branch. Inside, we check (x < 20 AND y > 5). Since x is 25, x < 20 is false. Because of AND, the entire compound expression is false regardless of y. We go to the ELSE branch and display “beta.”
B) “alpha” would require both x < 20 and y > 5 to be true, but x is 25 so x < 20 fails. C) “gamma” is in the outer ELSE branch, which only runs when x ≤ 10. D) “delta” is also in the outer ELSE branch.
Students see y > 5 is true and assume the AND expression passes. With AND, both sides must be true. Since x < 20 is false, the AND fails immediately.
When you see nested IF statements with AND or OR, draw a decision tree. Mark each branch with the conditions that must be true to reach it.
Keep Practicing!
Consistent daily practice is the key to AP CSP success.
AP CSP Resources Get 1-on-1 Help