Unit 2 Cycle 1 Day 12: While Loop with Condition Change
Share
While Loop with Condition Change
Section 2.8 — While Loops
Key Concept
The condition in a while loop must eventually become false for the loop to terminate. The loop body typically modifies a variable that the condition checks: incrementing a counter, shortening a string, or changing a boolean flag. On the AP exam, pay attention to what changes inside the loop and how it affects the condition. A common pattern is a loop that reads or processes until a sentinel value is reached. Always determine the exact iteration where the condition becomes false.
Consider the following code segment.
What is printed as a result of executing the code segment?
Answer: (B) 7
n halves each iteration: 128→64→32→16→8→4→2→1. That is 7 divisions. When n reaches 1, the condition 1 > 1 is false and the loop ends. count = 7.
Why Not the Others?
(A) 128 requires 7 halvings to reach 1, not 6. 2^7 = 128.
(C) 8 halvings would bring 256 to 1, not 128.
(D) 128 is the starting value of n, not related to count.
Common Mistake
This loop counts how many times you can divide n by 2 before reaching 1. This is essentially computing log base 2. For 128 = 2^7, the answer is 7.
AP Exam Tip
When a loop divides by 2 each iteration, think in powers of 2. The loop count equals the exponent: 2^count = starting value.