Counting with a for loop
A while loop repeats as long as a condition is true. When you already know how a loop should count — start here, stop there, step by this much — a for loop gathers those three pieces into one header so the reader sees the whole plan at once.
The header has three parts separated by semicolons:
- Initialization runs exactly once, before anything else.
- Boolean condition is checked before every iteration, including the first. If it is false, the body is skipped and the loop ends.
- Update runs after each execution of the body, then the condition is checked again.
for (int i = 0; i < 5; i++) { System.out.println("Lap " + i);}Three patterns you will reuse
Counting down
for (int t = 3; t >= 1; t--) { System.out.print(t + "... ");}System.out.println("Liftoff!");The loop variable can decrease. Output: 3... 2... 1... Liftoff!
Accumulating a total
int n = 6;int total = 0;for (int i = 1; i <= n; i++) { total += i;}// total is 21 (1 + 2 + 3 + 4 + 5 + 6)Declare the accumulator before the loop so it survives every iteration and is still available afterwards.
Rewriting as a while loop
// for loopfor (int k = 0; k < 3; k++) { System.out.println(k);} // equivalent while loopint k = 0;while (k < 3) { System.out.println(k); k++;}Any for loop can be rewritten as an equivalent while loop by moving initialization above and the update to the end of the body.
Predict before you run
Commit to an answer first, then check. Explaining why you were wrong is where most learning happens.
Trace every check and update
Step through the loop one action at a time. Notice the condition is checked five times but the body runs only four.
int sum = 0;for (int i = 1; i <= 4; i++) { sum += i;}System.out.println(sum);Step 1 of 12 · line 1
Declare sum and initialize it to 0.
| Step | Line | sum | i | What happens |
|---|---|---|---|---|
| 1 | 1 | 0 | — | Declare sum and initialize it to 0. |
Find the off-by-one error
This program should print how many even numbers are between 1 and 10 inclusive (the answer is 5). It prints 4 instead.
int count = 0;for (int n = 1; n < 10; n++) { if (n % 2 == 0) { count++; }}System.out.println(count); // should count evens 1–10Which line contains the logic error?
Apply it in a lab
Vowel Counter
Topics 2.8 · 2.10Use a for loop with substring to traverse a String and count its vowels. Work through specification, algorithm, code, trace, tests, explanation and reflection.
- Write a for loop that prints the multiples of 5 from 5 to 50.
- Write a for loop that computes the product 1 × 2 × … × 8 using an int accumulator.
- Rewrite your answer to (1) as a while loop and explain which version is clearer.
Common misconceptions
Reflect
Your reflection stays in this browser tab only and is cleared when you leave the page. Saving to your account arrives in Stage 2.