2.2.16 Traversing an Array With a for Loop

Overview

A for loop can visit every element of an array using its current index. The loop starts at zero, checks against Length, and increments after reading. This pattern adapts to arrays of different lengths without rewriting the bound.

int[] counts = { 2, 4, 6 };
for (int i = 0; i < counts.Length; i++)
{
    Console.WriteLine(counts[i]);
}
Use Length as the Boundary
Activity diagram for traversing an array with a for loop: use length as the boundary.
Use Length as the Boundary
  • New
  • Changed
  • Removed

The body reads counts[0], counts[1], and counts[2]. When i becomes 3, the condition fails before any counts[3] access. If counts has length zero, the body never runs.

The loop index identifies positions; the array elements hold values. Do not confuse increasing i with changing counts[i]. This loop reads each item but does not alter the array.

Trace the Outcome

Record i and counts[i] on each pass. Explain why the condition uses `<` instead of `<=`, and why the update belongs after the read.