Unit 2 Cycle 2 Day 27: Complex Conditional and Loop Interaction
Share
Complex Conditional and Loop Interaction
Section Mixed — Review: All Unit 2
Key Concept
Advanced combined problems integrate everything from Unit 2: nested conditionals with compound boolean expressions inside nested loops that process strings. The AP exam's most challenging Unit 2 questions require tracking 4-5 variables simultaneously through nested iteration with branching logic. The key to success is maintaining a disciplined trace table and not taking shortcuts. Each line of code must be evaluated with the current variable values, not with assumed or estimated values.
Consider the following code segment.
What is printed as a result of executing the code segment?
Answer: (A) 3
i=1(odd): result=0+1=1. i=2(even): result=1-2=-1. i=3(odd): result=-1+3=2. i=4(even): result=2-4=-2. i=5(odd): result=-2+5=3.
Why Not the Others?
(B) The alternating pattern adds odd numbers and subtracts even: 1-2+3-4+5 = 3, not -3.
(C) 15 would be the sum without any subtraction (1+2+3+4+5).
(D) 1 would be the result of a different alternating pattern.
Common Mistake
When a loop alternates between addition and subtraction based on even/odd, trace each iteration. The sign alternates: +1, -2, +3, -4, +5 = 3.
AP Exam Tip
For alternating-operation loops, write out each term with its sign before computing. This prevents sign errors.