Unit 2 Cycle 2 Day 18: Nested Conditional Logic
Share
Nested Conditional Logic
Section 2.4 — Else-If Statements
Key Concept
Nested conditional logic with multiple levels of if-else creates complex decision trees. When tracing, follow the execution path exactly: evaluate the outermost condition first, then follow only the branch that applies, ignoring all else branches that are not taken. A common AP exam question presents deeply nested conditionals and asks what output is produced for specific input values. Draw the decision tree if needed — it makes the execution path clearer than reading indented code.
Consider the following code segment.
What is printed as a result of executing the code segment?
Answer: (B) 7
a=3, b=7, c=5. a > b: 3 > 7 is false, go to else. b > c: 7 > 5 is true, max = b = 7. This algorithm finds the maximum of three values using nested ifs.
Why Not the Others?
(A) a=3 is not the maximum of 3, 7, 5.
(C) c=5 is not the maximum. b=7 is larger.
(D) The code compiles. Single-statement if bodies without braces are valid (though not recommended).
Common Mistake
This is the standard find-max-of-three algorithm. First compare a and b to determine which branch to take, then compare the winner against c.
AP Exam Tip
Trace nested ifs by following the exact path. At each if, determine the branch taken, then trace only that branch. Do not trace branches that are skipped.