while & for Loops
- Trace a `while` loop, tracking the condition and update each pass
- Read the three parts of a `for` loop header: initialize, test, update
- Accumulate a running total or count across loop iterations
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.
Trace this code: int sum = 0; then for (int i = 1; i <= 4; i++) { sum += i; } then System.out.println(sum);
- 1.Start with
sum = 0. i = 1:sum += 1makes sum1. - 2.i = 2:
sum += 2makes sum3. i = 3:sum += 3makes sum6. - 3.i = 4:
sum += 4makes sum10. Next i = 5 fails the testi <= 4, so the loop stops.
10 — the sum 1 + 2 + 3 + 4.What does this print? `int sum = 0;` then `for (int i = 1; i <= 4; i++) { sum += i; }` then `System.out.println(sum);`
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.
What does this print? `int i = 0;` then `while (i < 3) { System.out.print(i); i++; }`
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