Privacy note: We capture your IP address to provide customised and focused services. See our Privacy Policy.

AP Computer Science A: Deep Dive and FRQ Mastery — Alpha School

Lesson 7: While Loops and for Loops

A loop repeats a block of code while a condition holds, and it is how programs handle repetition without writing the same statements dozens of times. Java has two main loop forms, and choosing between them is a matter of what you know before the loop starts. A while loop is used when the number of repetitions is not known in advance: it tests its condition before each iteration, and stops as soon as the condition becomes false. A for loop is used when the number of repetitions is known, or when you are stepping through a range of values, and it packs the initialization, the test, and the update into one line.

Every loop needs three parts, and forgetting one is the source of the classic loop bugs. The initialization sets up the loop variable, the condition decides whether to run another iteration, and the update moves the loop toward its end. In a while loop these are spread across separate statements, and a missing update produces an infinite loop, a loop that never ends because its condition never becomes false. In a for loop they sit together in the header — for (int i = 0; i < 10; i++) — which makes the structure visible at a glance and the update hard to forget.

The two loop forms are interchangeable in what they can do, and you will sometimes rewrite one as the other to check your understanding. A for loop can always be written as a while loop by moving the initialization before it and the update to the end of its body, and a while loop can be written as a for loop when its initialization and update are simple. The choice is about readability: use a for loop when you are counting or stepping through a fixed range, and a while loop when you are waiting for something to happen, such as reading input until a sentinel value appears. A sentinel is a special value that signals the end of input, such as −1 for a list of positive numbers.

Tracing a loop means writing down the loop variable and any other changing values at the end of each iteration, in a small table. The most common tracing errors are the off-by-one error — running one time too many or too few, usually from confusing < with <= — and the infinite loop, usually from an update that never moves the condition toward false. Check the boundaries explicitly: what is the loop variable on the first iteration, what is it on the last, and how many iterations run in total? For a loop from i = 0 while i < 10, the answer is ten iterations, with i from 0 to 9.

A do-while loop, which Java also provides, tests its condition after the body rather than before, so it always runs at least once. It is the right choice when the body must execute before the test makes sense, such as asking the user for input and repeating until the answer is valid. You will use while and for far more often, but recognizing the do-while form keeps you from being surprised when you meet it in someone else's code.

A worked example

Worked example: the two fragments below both print the numbers 1 to 5. The for loop is the natural choice here because the count is known, while the while loop spells out the same three parts separately. Trace either one and you get the same output.

for (int i = 1; i <= 5; i++)
{
    System.out.print(i + " ");
}
System.out.println();
int j = 1;
while (j <= 5)
{
    System.out.print(j + " ");
    j++;
}
System.out.println();  // both print: 1 2 3 4 5

In the for loop, i is initialized to 1, the condition i <= 5 is tested, the body prints i, and i is incremented, repeating until i is 6 and the condition fails. In the while loop, j is initialized before the loop, the condition is tested at the top, and the update j++ sits at the end of the body — move it before the print and the output would be 2 3 4 5 6 instead. In free-response answers, a loop trace table with one row per iteration is the clearest way to show your working, and it is what markers expect.

Key Terms

Loop
A statement that repeats a block of code while a condition holds.
while loop
A loop that tests its condition before each iteration; used when the count is unknown.
for loop
A loop packing initialization, condition, and update in its header; used when the count is known.
Infinite loop
A loop whose condition never becomes false, so it runs forever.
Sentinel
A special value signalling the end of input.
Off-by-one error
Running a loop one time too many or too few, usually from a wrong boundary.

Discussion Questions

  1. When would you choose a while loop instead of a for loop?
  2. What three parts does every loop need, and what happens if one is missing?
  3. How do you check a loop for an off-by-one error?

Practice Questions

  1. How many times does for (int i = 0; i < 5; i++) run its body?
  2. What is wrong with while (x > 0) { System.out.println(x); } if x is never changed inside the body?
  3. Write a for loop that prints the numbers 10 down to 1.
  4. What values does int i print in for (int i = 2; i <= 8; i += 2)?
  5. A loop reads numbers until the user enters −1. What is −1 called here?
Show answers
  1. 5 times, with i = 0, 1, 2, 3, 4.
  2. It is an infinite loop, because the condition x > 0 never becomes false.
  3. for (int i = 10; i >= 1; i--) { System.out.print(i + " "); }
  4. 2, 4, 6, 8.
  5. A sentinel value.
Keep reading to complete this lesson