java-foundations 12 min read

for Loops — A First Look

Running the same code several times with a counter

Reading: Reges & Stepp: Ch. 2 §2.3 (the for loop)

Every program you’ve written so far has run each line exactly once. To print ten stars you wrote ten println lines. To sum five numbers you wrote five += lines. This works for small N. It breaks the moment N is large or unknown — and “unknown” is most of real programming.

The for loop lets a block of code run a chosen number of times. This is a first-look lesson: you will see the syntax, trace one, and write a couple of common patterns. Later lessons go deeper — this one just opens the door.

In a nutshell

A for loop repeats a block of code a known number of times. Three parts control it: the initialization (usually creates a counter), the condition (keeps looping while true), and the update (runs after each iteration). When the condition becomes false, the loop ends.

A loop variable like i behaves like any other int variable — you can read it, use it in expressions, and watch its value change as the loop runs. Tracing a loop by hand is the same skill as tracing conditionals, just with repetition.

By the end of this lesson you will be able to read and trace a simple for loop, write one that repeats N times, and recognize the accumulator pattern.

Quick reference

Syntax

for (initialization; condition; update) {
    // body — runs once each iteration, while condition is true
}

The canonical counting loop

for (int i = 1; i <= 10; i++) {
    System.out.println(i);
}
// prints 1, 2, 3, ..., 10 each on its own line

Reading it: “start i at 1; keep going while i <= 10; after each iteration, add 1 to i.”

How each iteration runs

  1. Evaluate the initialization once, before anything else.
  2. Check the condition. If false, exit the loop.
  3. Run the body.
  4. Run the update.
  5. Go back to step 2.

Common patterns

Pattern Shape
Repeat N times for (int i = 0; i < N; i++) { ... }
Count 1 to N for (int i = 1; i <= N; i++) { ... }
Count down for (int i = N; i >= 1; i--) { ... }
Even numbers up to N for (int i = 0; i <= N; i += 2) { ... }

Off-by-one rule of thumb. If i starts at 0, use i < N. If i starts at 1, use i <= N. Either form runs the body exactly N times; mixing them (i = 0; i <= N or i = 1; i < N) gives you one too many or one too few iterations. Worked out at length in the “Off-by-one” section below.


Deep dive

1. The shape of a for loop

for (int i = 1; i <= 5; i++) {
    System.out.println("Hello");
}

Five words, five “Hello”s. Each of the three parts in the parentheses does exactly one thing:

  • int i = 1 — runs once, at the start. Creates a new variable i and sets it to 1.
  • i <= 5 — checked before every iteration. If true, run the body. If false, stop.
  • i++ — shorthand for i = i + 1. Runs after every iteration.

The variable i exists only inside the loop. Once the loop ends, i is gone — you can’t read it from the next line. Like a method parameter, i has a scope limited to its block.

Loop counters conventionally start at 0. When you’re writing a loop to repeat N times, for (int i = 0; i < N; i++) is the standard shape. It is the form that lines up naturally with array indexing (covered later) and with most programmer muscle memory.

2. Tracing a loop

Trace:

int total = 0;
for (int i = 1; i <= 3; i++) {
    total = total + i;
}
System.out.println(total);
Step i total Action
Start 1 0 i = 1 initialized; condition 1 <= 3 is true
After body (iter 1) 1 1 total = 0 + 1 = 1
After update 2 1 i++ makes i = 2; condition 2 <= 3 true
After body (iter 2) 2 3 total = 1 + 2 = 3
After update 3 3 i = 3; condition 3 <= 3 true
After body (iter 3) 3 6 total = 3 + 3 = 6
After update 4 6 i = 4; condition 4 <= 3 false — exit
Print 6 prints 6

This is the accumulator pattern: you start a running total at zero, add to it each iteration, and read the final result after the loop. You will use this shape constantly.

Check Your Understanding
How many times does the body of this loop run?
for (int i = 0; i < 10; i++) {
    System.out.println(i);
}
A9 times
B10 times
C11 times
Dinfinite times
Answer: B. i starts at 0 and runs while i < 10, taking values 0, 1, 2, ..., 9. That's 10 iterations. The loop prints 0 through 9. When i becomes 10, 10 < 10 is false and the loop exits. Off-by-one reminder: i < N gives you N iterations, not N-1.

3. Common patterns

Repeating something N times. The workhorse shape:

for (int i = 0; i < 5; i++) {
    System.out.println("*");
}
// prints 5 stars

Building up a sum. The accumulator pattern:

int sum = 0;
for (int i = 1; i <= 100; i++) {
    sum = sum + i;
}
// sum now holds 1 + 2 + ... + 100 = 5050

Counting down. Sometimes you need to iterate in reverse:

for (int i = 10; i >= 1; i--) {
    System.out.println(i);
}
// prints 10, 9, 8, ..., 1

Self-check. Write a for loop that prints the first 10 even numbers (2, 4, 6, 8, 10, 12, 14, 16, 18, 20).

Answer
for (int i = 2; i <= 20; i += 2) {
    System.out.println(i);
}

Or equivalently, count 1 to 10 and print i * 2 each time:

for (int i = 1; i <= 10; i++) {
    System.out.println(i * 2);
}

Both work. The second is easier to modify if you later want “first N even numbers” for arbitrary N.

Off-by-one — the perennial loop bug

Two ways to loop ten times:

for (int i = 0; i <  10; i++) { ... }   // i = 0, 1, ..., 9    — 10 iterations
for (int i = 1; i <= 10; i++) { ... }   // i = 1, 2, ..., 10   — 10 iterations

Either is fine. But you often see students write for (int i = 0; i <= 10; i++) and get 11 iterations — one too many. Or for (int i = 1; i < 10; i++) and get 9 — one too few.

Rule of thumb: if i starts at 0, use i < N. If i starts at 1, use i <= N. (Same rule is also boxed at the top of the Quick Reference — it is worth burning into muscle memory.)

Reflection. Write a for loop that prints the first N positive multiples of 3 (so for N = 4 it would print 3, 6, 9, 12). Now adapt it to print the first N positive multiples of K for any K. What did you have to change between the two versions, and what did you keep the same? What does that comparison suggest about when to parameterize a value versus when to hard-code it?


Before you leave

A for loop is three knobs — start, condition, update — controlling how many times the body runs. Most of CS1 loops come in two shapes: “repeat N times” and “accumulate a running total.” You’ll use both of those constantly from here on.

Next: loops in depthwhile loops, nested loops, loop conditions driven by user input, and when each shape is the right tool. This lesson was the warmup.

Want to practice? The Week 4 quiz-prep set on the practice platform has tracing problems that extend directly from this lesson.