๐ 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 exactlyntimes.for (int i = 1; i <= n; i++)runs exactlyntimes.for (int i = 0; i <= n; i++)runsn + 1times โ the off-by-one.for (int i = 0; i < n; i += 2)runsceil(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 CodeLoop repCounting, accumulation, digit surgery, nested construction.
5 challenges ยท ยท ~50 min