Unit 2 Cycle 2 Day 12: While Loop with Complex Condition
Share
While Loop with Complex Condition
Section 2.8 — While Loops
Key Concept
While loops with complex multi-part conditions require evaluating the entire condition before each iteration. A condition like x > 0 && str.length() < 10 && !done must have all three parts true to continue. If any part becomes false, the loop exits. The AP exam creates scenarios where different parts of the condition become false at different times, and the exit value of variables depends on which part triggered the exit. Trace by evaluating the full condition at the top of each iteration.
Consider the following code segment.
What is the value of steps when x starts at 4?
Answer: (A) 2
x=4: even, x=2, steps=1. x=2: even, x=1, steps=2. x=1: loop ends. steps = 2.
Why Not the Others?
(B) Only 2 divisions are needed: 4→2→1.
(C) After one step x=2, which is not yet 1, so the loop continues.
(D) The loop reaches x=1 after just 2 steps.
Common Mistake
This is the Collatz conjecture. For powers of 2, the path is simple: keep dividing by 2. For 4: two steps. The odd-number branch (3x+1) is not triggered when starting with an even number that is a power of 2.
AP Exam Tip
For complex while loops, trace with simple inputs first. Powers of 2 simplify the Collatz sequence because only the even branch executes.