How does a while loop repeat a block of code, and how do you avoid an infinite loop?
Topic 4.1 while Loops: use a while loop to repeat a block of statements while a boolean condition remains true, with correct initialisation, condition and update to avoid infinite or off-by-one loops.
A focused answer to AP CSA Topic 4.1, covering while loop syntax, the initialise/test/update pattern, why each loop control variable must change, infinite loops and off-by-one errors, and how to trace iterations, with a fully worked example.
Reviewed by: AI editorial process; not yet individually human-reviewed
Have a quick question? Jump to the Q&A page
Jump to a section
What this topic is asking
The College Board (Topic 4.1) wants you to write and trace a while loop: a structure that repeats a block of statements as long as a boolean condition stays true. The skill is managing the three parts that every correct loop needs - initialise, test, update - so the loop runs the right number of times and eventually stops. Infinite loops and off-by-one errors are the classic failures, and tracing iteration counts is a staple of the multiple-choice section.
Syntax and the three parts
int i = 0; // 1. initialise
while (i < 5) { // 2. test the condition
System.out.println(i);
i = i + 1; // 3. update
}
Every reliable loop has these three parts:
- Initialise the loop control variable before the loop.
- Test a boolean condition at the top of each pass.
- Update the control variable inside the body so the condition eventually fails.
Why the update is essential
Without an update that moves toward the stopping condition, the loop repeats forever. while (i < 5) { System.out.println(i); } with no i = i + 1 prints 0 endlessly. The update is what guarantees termination.
Off-by-one errors
while (i < 5) starting at i = 0 runs for i = 0, 1, 2, 3, 4 - five times. while (i <= 5) would run six times. Decide carefully whether the boundary value should be included.
Loops that run zero times
Because the test comes first, a loop can run zero times. while (i < 5) with i already 5 skips the body entirely. Always consider the empty case when you reason about a loop. This pre-test behavior is what makes while the right choice when you do not know in advance how many repetitions are needed: the loop keeps going only as long as the condition holds, and stops the instant it fails - even before the first pass. A for loop (Topic 4.2) tests its condition the same way, so the same zero-iteration reasoning applies there too.
Try this
Q1. How many times does while (i < 3) run if i starts at 0 and increases by 1 each pass? [1 point]
- Cue. Three times, for
i = 0, 1, 2; the loop stops whenireaches 3.
Q2. Explain what causes an infinite loop in a while statement and how to prevent it. [2 points]
- Cue. The loop never ends if the body fails to change the control variable toward making the condition
false; include an update (such as incrementing) that guarantees termination.
Exam-style practice questions
Practice questions written in the style of College Board exam questions on this dot point, with worked answer explainers. The year tag is the paper they imitate, not the source.
AP 2022 (style)1 marksMultiple choice. Consider the following code segment.
```java
int i = 1;
int sum = 0;
while (i <= 4) {
sum = sum + i;
i = i + 1;
}
System.out.println(sum);
```
What is printed?
(A) `10`
(B) `6`
(C) `15`
(D) `4`
(E) Nothing; the loop runs forever.
Show worked answer →
The answer is (A).
The loop runs while i <= 4. It adds i to sum, then increments i. Iteration 1: i=1, sum=1. Iteration 2: i=2, sum=3. Iteration 3: i=3, sum=6. Iteration 4: i=4, sum=10. Then i becomes 5; 5 <= 4 is false, so the loop stops. sum is 1+2+3+4 = 10. (B) stops one iteration too early; (C) adds 5 as well; (E) is wrong because i is updated each pass.
Markers reward tracing the four iterations and noting the loop ends when i reaches 5.
AP 2020 (style)4 marksFree response (code writing). A positive `int` variable `n` is given. Write a code segment using a while loop that prints each power of 2 (1, 2, 4, 8, ...) that is less than or equal to `n`, one per line. For example, if `n` is 10, the output is 1, 2, 4, 8 on separate lines.
Show worked answer →
A 4-point question testing while-loop control with a multiplicative update.
int power = 1;
while (power <= n) {
System.out.println(power);
power = power * 2;
}
Point 1: initialise power to 1 before the loop. Point 2: the condition power <= n continues while the current power does not exceed n. Point 3: print power inside the loop. Point 4: the update power = power * 2 doubles each pass, guaranteeing the loop eventually ends. Omitting the update would loop forever; using power = power + 2 would print the wrong values.
Related dot points
- Topic 4.2 for Loops: use a for loop, whose header combines initialisation, a boolean condition and an update, to repeat a block a controlled number of times, and convert between for and while loops.
A focused answer to AP CSA Topic 4.2, covering for-loop header syntax (init; condition; update), the order in which the three parts run, counting iterations, equivalence with while loops, common patterns, and tracing, with a fully worked example.
- Topic 4.4 Nested Iteration: write and trace nested loops, where an inner loop runs in full on each pass of an outer loop, and count the total number of inner-loop iterations.
A focused answer to AP CSA Topic 4.4, covering nested loops, how the inner loop completes fully on each outer pass, counting total iterations (including triangular patterns where the inner bound depends on the outer variable), and tracing nested output, with a fully worked example.
- Topic 4.5 Informal Code Analysis: determine the number of times a statement executes in a loop or nested loop by counting iterations, without using formal big-O notation.
A focused answer to AP CSA Topic 4.5, covering how to count statement executions in single and nested loops, the effect of step size and start/end bounds, conditional statements inside loops, and triangular versus rectangular counts, with a fully worked counting example.
- Topic 4.3 Developing Algorithms Using Strings: traverse a String with a loop using length, substring and indexOf to implement standard algorithms such as counting characters, searching for a pattern and building a new String.
A focused answer to AP CSA Topic 4.3, covering String traversal with a for loop, extracting one character with substring, the standard counting, searching and accumulation patterns, the half-open index range, and bounds safety, with a fully worked example.
- Topic 3.2 if Statements and Control Flow: use a one-way if statement so that a block of code runs only when its boolean condition is true, and trace the resulting flow of control.
A focused answer to AP CSA Topic 3.2, covering the syntax of a one-way if statement, the role of the boolean condition, why braces matter, the dangling-statement trap, and how control flows through and past the if, with a fully traced worked example.
Sources & how we know this
- AP Computer Science A Course and Exam Description — College Board (2025)