AP® Computer Science A · Unit 2 · Topic 2.7
The while Loop and Its Three Moving Parts
A while loop repeats its body as long as a condition stays true, and it needs three parts working together: a variable set up before the loop, a condition checked before each pass, and an update that eventually makes the condition false.
A while loop has three moving parts, and all three have to work together or the loop either never runs or never stops. First, you set up a variable before the loop starts, often called a counter. Second, the loop tests a condition using that variable, and it checks this condition before every single pass through the body, including the very first one. Third, something inside the body has to update the variable, moving it closer to making the condition false. Leave out the update, or update the wrong variable, and the condition stays true forever, which gives you an infinite loop.
Picture the three parts as a cycle: setup happens once, then test, then body, then update, then back to test. The loop keeps cycling through test-body-update until the test comes back false, at which point it skips the body and moves on. Because the test runs before the body each time, a while loop can run zero times if the condition is already false at the start. This is different from a loop that guarantees at least one pass.
This three-part structure is exactly what you track in a trace table: one row per pass, showing the variable's value, whether the test passes, and what the update does. Understanding while loops here sets up for loops next, which package the same three parts (setup, test, update) into one line, and for comparing while loops to do-while loops, which test after the body instead of before.
Key terms
- initialization
- The statement before the loop that sets the starting value of the loop variable.
- condition
- The boolean expression checked before each pass through the loop body.
- update
- The statement inside the loop body that changes the loop variable, usually moving it toward making the condition false.
- infinite loop
- A loop whose condition never becomes false, so the body keeps repeating forever.
- trace table
- A table that tracks a variable's value and the loop condition's result for each pass of a loop.
Watch it explained
- How it worksHow do the setup, the test, and the update circle around inside a while loop?
- Worked exampleTrace int i = 1; while (i ≤ 5) { System.out.print(i); i++; } and find what prints.
- How it worksHow does a while loop check its condition before the body ever runs even once?
- Worked exampleFind how many times a while loop with i starting at 0 and testing i < 7 runs its body.
Check yourself
End of topic.