Unit 2 Cycle 2 Day 7: While Loop State Tracking
Share
While Loop State Tracking
Section 2.8 — While Loops
Key Concept
Complex while loop state tracking problems involve multiple variables that change each iteration. The loop condition may depend on one variable while the body modifies several. The AP exam presents loops where tracking requires careful attention to which variable is updated first, since later statements in the body may use the already-updated value. Create a trace table with columns for every variable and update them in statement order, not simultaneously. The final values after the loop exits reveal the answer.
Consider the following code segment.
What is printed as a result of executing the code segment?
Answer: (D) 7 34
This generates Fibonacci: (a,b) starts at (1,1). Each iteration: temp=a+b, a=b, b=temp. Sequence: (1,1)→(1,2)→(2,3)→(3,5)→(5,8)→(8,13)→(13,21)→(21,34). After 7 iterations: a=21, b=34. Check: 21+34=55, not <50. Loop ends. count=7, b=34.
Why Not the Others?
(A) 55 is a+b after the loop ends, not the value of b. b is 34.
(B) After 6 iterations, a=13, b=21, a+b=34 < 50, so the loop continues for a 7th iteration.
(C) The loop stops when a+b >= 50. After count=7, a+b=55 >= 50, so count never reaches 8.
Common Mistake
Track multiple variables simultaneously using a table. Fibonacci-style loops are common on the AP exam and require careful tracking of the temp variable.
AP Exam Tip
For multi-variable loops, create a table with columns for each variable. Update all columns each iteration. Check the loop condition at the top of each row.