๐ WAYPOINT LESSON
Counting iterations
โญ beginnerโณ 12 min read๐ Lesson 66 of 256
Dependent inner bounds, triangle vs square, sequential vs nested loops.
Counting iterations exactly โ the trace skill applied to loops:
int total = 0;
for (int i = 0; i < n; i++) {
for (int j = i + 1; j < n; j++) {
total++; // how many times?
}
}
The inner loop depends on the outer one: for i = 0 it runs n-1
times, i = 1 โ n-2, ..., total n(n-1)/2 โ still O(nยฒ), but
half the work. Two loops over the same n in sequence is n + n = 2n โ linear. Two loops nested is n * n. The shape of the
nesting decides the class, not the number of loops.
The other counting traps:
j < nvsj <= nโ one iteration difference, one test difference.- Inner bound
j < ivsj < nโ triangle vs square. - Loop variables mutated inside the body โ the iteration count changes; trace it, don't pattern-match.