Skip to main content
๐Ÿ“œ WAYPOINT LESSON

for loops and counting

โญ beginnerโณ 12 min read๐Ÿ“ Lesson 18 of 256

The for header, iteration counts, accumulators and counters.

The for loop packs init / test / update into one header โ€” the workhorse:

for (int i = 0; i < 5; i++) {
    System.out.print(i);
}
// prints 01234

Execution order: init once โ†’ test โ†’ body โ†’ update โ†’ test โ†’ ... Exactly equivalent to the while version, but the three loop-control pieces are visible in one line, so nothing can be forgotten.

Counting problems (how many times does the loop run?) are pure exam material:

  • for (int i = 0; i < n; i++) runs exactly n times.
  • for (int i = 1; i <= n; i++) runs exactly n times.
  • for (int i = 0; i <= n; i++) runs n + 1 times โ€” the off-by-one.
  • for (int i = 0; i < n; i += 2) runs ceil(n / 2.0) times.

Accumulator and counter inside loops:

int total = 0, count = 0;
for (int i = 1; i <= 10; i++) {
    if (i % 2 == 0) {
        total += i;
        count++;
    }
}
// total 30, count 5

The accumulator is declared outside the loop; resetting it inside is a favorite exam bug.

โšก Now practice

Ready to Code
Loop repCounting, accumulation, digit surgery, nested construction.
5 challenges ยท ยท ~50 min