Unit 2 Cycle 2 Day 1: Nested If vs Compound Boolean
Share
Nested If vs Compound Boolean
Section 2.5 — Compound Boolean
Key Concept
A nested if inside another if can always be rewritten as a single if with a compound boolean using &&. The code if (a) { if (b) { ... } } is equivalent to if (a && b) { ... }. However, when else branches are involved, the equivalence becomes more complex. A nested structure allows different else actions for each level, while a compound condition has a single else for the entire expression. The AP exam tests whether two code segments produce identical results.
Consider the following two code segments.
For which values of x do Segments A and B produce different output?
Answer: (D) They always produce the same output.
Nested ifs with no else are logically equivalent to a compound AND. Segment A checks x > 0 then x < 100. Segment B checks both simultaneously. Both print "valid" only when 0 < x < 100.
Why Not the Others?
(A) Both segments print "valid" when x=50 (0 < 50 < 100).
(B) Neither segment prints anything when x=0 (0 is not > 0).
(C) Neither prints when x=100 (100 is not < 100).
Common Mistake
Nested ifs (without else) are equivalent to &&. However, adding an else to the nested version makes them behave differently. The equivalence only holds when there are no else branches.
AP Exam Tip
On the AP exam, expect questions asking you to identify equivalent code. Nested ifs without else = AND. But nested ifs with else create more complex branching.