AP Computer Science A · Unit 2: Selection & Iteration
2.8 While Loops
While loop basics
A while loop repeats a block of code as long as its boolean condition is true. Syntax: `while (condition) { statements; }`. Before each iteration, Java checks the condition — if false, the loop body never runs (or stops running), and control passes to the code after the loop.
Avoiding infinite loops
The loop body must eventually make the condition false, or it becomes an infinite loop. This usually requires updating a variable used in the condition (like incrementing a counter) inside the loop body. Forgetting this update is a common bug that causes programs to run forever.
While vs. for loops
While loops are ideal when the number of iterations is unknown ahead of time (e.g., reading input until a sentinel value appears), while for loops suit a known, fixed number of iterations. Both can achieve the same repetition, but while loops offer more flexible control over when to stop.
Key terms
- While loop
- A control structure that repeats a block of code as long as a boolean condition is true, checked before each iteration.
- Infinite loop
- A loop whose condition never becomes false, causing it to run forever; usually caused by forgetting to update a controlling variable.
- When to use a while loop
- When the number of iterations is unknown in advance, such as reading input until a sentinel value is found.
- While loop syntax
- while (condition) { statements; } — the condition is evaluated before each pass through the loop body.
- Loop control variable
- A variable used in the loop's condition that must be updated inside the loop body to eventually make the condition false.
Try an AP-style question
Code
int n = 1;
while (n < 20)
n *= 2;What is n after the loop?
- 64
- 32
- 16
- 20
Show the answer
B. 1, 2, 4, 8, 16, 32.
Practice 8 AP-style questions with instant explanations, flashcards and spaced review.
Study 2.8 free in APrep