2.2.6 Traversing a Sequence With a Loop

Overview

Traversing means visiting each position in a sequence. For a Zoo record of daily portions, an index starts at zero and advances until it reaches the array length. The loop body uses the current index to read one value.

double[] portions = { 0.5, 0.75, 1.0 };
for (int i = 0; i < portions.Length; i++)
{
    double currentPortion = portions[i];
    Console.WriteLine(currentPortion);
}
Visit Values in Order
Activity diagram for traversing a sequence with a loop: visit values in order.
Visit Values in Order
  • New
  • Changed
  • Removed

The body reads 0.5, then 0.75, then 1.0. When i becomes 3, `i < portions.Length` is false. The last valid index is 2. Starting at zero and using `< Length` visits every existing item exactly once.

A sequence can contain any number of values; the loop gets its stop boundary from Length rather than from a manually copied number. That keeps traversal correct when the array size changes.

Trace the Outcome

Trace the index and currentPortion for all three passes. If the array is empty, its Length is zero and the body is skipped.