Unit 2 Cycle 1 Day 23: If-Else with Loop Interaction
Share
If-Else with Loop Interaction
Section Mixed — Review: Conditionals and Loops
Key Concept
When conditionals appear inside loops, the condition is evaluated on every iteration but may only be true for some iterations. This creates selective processing where the loop body does different things depending on the current state. A common pattern: loop through numbers 1 to n, and inside the loop, use an if to check if the number is even, odd, divisible by some value, etc. The AP exam combines these patterns to create code that produces non-obvious output requiring careful iteration-by-iteration tracing.
Consider the following code segment.
What is printed as a result of executing the code segment?
Answer: (B) 26
Trace each iteration: i=0: x=1 (odd), x*=2 → x=2. i=1: x=2 (even), x+=3 → x=5. i=2: x=5 (odd), x*=2 → x=10. i=3: x=10 (even), x+=3 → x=13. i=4: x=13 (odd), x*=2 → x=26.
Why Not the Others?
(A) 16 would require a different sequence of operations than what the trace produces.
(C) 13 is x after iteration i=3, but there is one more iteration remaining.
(D) 10 is x after iteration i=2, but there are still two more iterations.
Common Mistake
When a loop modifies a variable that affects conditional branching, each iteration may take a different path. You must trace every iteration; do not assume a pattern after 2-3 iterations.
AP Exam Tip
For loops with alternating conditions, trace every single iteration. The path through the if-else changes based on the current value of x.