← Back to course

while & for Loops

You’ll be able to

The while loop

A while loop repeats its body as long as its condition stays true, checking the condition before each pass. The body must eventually make the condition false — usually by changing a variable — or the loop runs forever. A counter pattern like int i = 0; while (i < 3) { ...; i++; } runs for i = 0, 1, 2 and stops when i reaches 3.

The for loop

A for loop packs three parts into its header: for (initialize; test; update). Java runs the initialize once, then before every pass checks the test, and after every pass runs the update. for (int i = 1; i <= 4; i++) therefore runs with i = 1, 2, 3, 4 and stops when the test i <= 4 becomes false at i = 5.

Accumulating results

A common loop job is to accumulate a value across iterations. Start an accumulator before the loop (int sum = 0;) and update it inside (sum += i;). After the loop the accumulator holds the combined result. The same pattern with count++ tallies how many times something happened. Also note print vs println: print stays on the same line, so repeated print calls run their output together.

for loop header
for (init; test; update) { body }
init runs once; test is checked before each iteration; body then runs; update runs after the body; repeat until test is false.
Worked example

Trace this code: int sum = 0; then for (int i = 1; i <= 4; i++) { sum += i; } then System.out.println(sum);

  1. 1.Start with sum = 0. i = 1: sum += 1 makes sum 1.
  2. 2.i = 2: sum += 2 makes sum 3. i = 3: sum += 3 makes sum 6.
  3. 3.i = 4: sum += 4 makes sum 10. Next i = 5 fails the test i <= 4, so the loop stops.
Answer: It prints 10 — the sum 1 + 2 + 3 + 4.
Checkpoint

What does this print? `int sum = 0;` then `for (int i = 1; i <= 4; i++) { sum += i; }` then `System.out.println(sum);`

Watch out

A while loop with no update is an infinite loop. Make sure some statement in the body eventually makes the condition false, or the program never ends.

Checkpoint

What does this print? `int i = 0;` then `while (i < 3) { System.out.print(i); i++; }`

On the exam

To trace a loop, make a small table with a column per variable and one row per pass. Writing the value after each iteration prevents off-by-one errors on the final count.

Answer the 2 checkpoints as you read.

Sign in to save your progress