Unit 2 Cycle 2 Day 12: While Loop with Complex Condition

Unit 2 Advanced (Cycle 2) Day 12 of 28 Advanced

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.

int x = 100; int steps = 0; while (x != 1) { if (x % 2 == 0) { x /= 2; } else { x = 3 * x + 1; } steps++; } System.out.println(steps);

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.

Review this topic: Section 2.8 — While Loops • Unit 2 Study Guide

More Practice

Related FRQs

Back to blog

Leave a comment

Please note, comments need to be approved before they are published.