Unit 2 Cycle 1 Day 11: While Loop Basics
Share
While Loop Basics
Section 2.8 — While Loops
Key Concept
A while loop repeatedly executes its body as long as its condition remains true. The condition is checked before each iteration, including the first — if the condition is initially false, the body never executes. This is called a pre-test loop. The loop body must change something that eventually makes the condition false; otherwise, the loop runs forever (infinite loop). On the AP exam, trace while loops by writing the condition value and variable states at the start of each iteration.
Consider the following code segment.
What is printed as a result of executing the code segment?
Answer: (B) 15
Trace: count=1,sum=1. count=2,sum=3. count=3,sum=6. count=4,sum=10. count=5,sum=15. count becomes 6, loop ends. Sum = 1+2+3+4+5 = 15.
Why Not the Others?
(A) This is 1+2+3+4 = 10, which would result from count < 5 (stopping before 5).
(C) This would just be the final value of count minus 1, not the sum.
(D) This would be the final value of count after the loop (count becomes 6, not printed).
Common Mistake
The accumulator pattern adds each value of count to sum. The loop runs for count = 1, 2, 3, 4, 5. After count becomes 6, the condition 6 <= 5 is false and the loop ends.
AP Exam Tip
For accumulator loops, trace the first 2-3 iterations, then look for a pattern. The sum 1+2+...+n = n(n+1)/2. For n=5: 5(6)/2 = 15.