Concepts / Working with Collections: Lists and Iteration

Working with Collections: Lists and Iteration

Iteration is the repeated execution of statements in a loop or recursive function, and understanding loop terminology is essential for writing correct loops.

  • Programming

A Loop in Motion

Iteration means executing statements repeatedly in a loop or recursive function. When a loop works with a collection such as a list, each repetition processes another position or element. To understand what the loop is doing, track the variables that control repetition and the variables that record results.

What do you think happens?

A list-processing loop begins at position 0 and moves forward by one position after each iteration. What position will it examine on the first three iterations?

  • 0, then 1, then 2
  • 1, then 2, then 3
  • 0, then 0, then 0
Reveal answer

Answer: 0, then 1, then 2

The position is initialized at 0 and incremented by one after each iteration. The update moves the loop to the next position.

Following Collection Positions

A useful way to trace list iteration is to place the collection positions beside their elements and then record the position used by each repetition. In this generated example, the loop begins at position 0 and advances one position at a time. The important pattern is not the particular values in the list; it is the changing relationship between the current position and the element selected there.

selectsselectsselectsPosition 0redredselected firstPosition 1blueblueselected secondPosition 2greengreenselected third
How does each loop iteration map a position to the corresponding list element?

The diagram shows three separate iterations: the first uses position 0, the second uses position 1, and the third uses position 2. Initialization establishes the first position, while incrementing establishes the movement from one position to the next.

The Loop State Record

Initialization assigns a starting value to a variable before the loop begins. A counter tracks how many times an event occurs by increasing by 1 or another fixed amount on each iteration. An accumulator builds a running total by adding values that may vary from one iteration to the next.

Loop conceptRoleTypical update
InitializationSets a starting value before repetition beginsAssign a starting value
CounterTracks how many times an event occursIncrease by 1 or another fixed amount
AccumulatorBuilds a running totalAdd the current value, which may vary
IncrementMoves a variable upward by a fixed amountIncrease by a fixed amount
DecrementMoves a variable downward by a fixed amountDecrease by a fixed amount

Roles of common loop variables and operations

A counter and an accumulator may both begin at 0, but they answer different questions. The counter asks how many events have occurred. The accumulator asks what total has been built from the values processed so far. Keeping those meanings separate makes a loop easier to trace and debug.

fixed increasefixed increaseadd 5add 1Counter: 0before iterationsTotal: 0before valuesCounter: 1after one eventTotal: 5after adding 5Counter: 2after two eventsTotal: 6after adding 1
What value does each variable hold after successive iterations, and how does an accumulator differ from a counter?

Updating Toward Termination

Every loop trace should include three questions: Where did the variable start? How does the loop update it? Does that update move it toward the stopping point? An increment moves a variable upward by a fixed amount. A decrement moves it downward by a fixed amount. The appropriate operation depends on the direction in which the loop must progress.

increaseincreasedecreasedecreasePosition 0initializedPosition 3initializedPosition 1incrementPosition 2decrementPosition 2continues forwardPosition 1continues backward
Where does a loop variable start, how is it changed after each iteration, and how do incrementing and decrementing affect progress?

The forward path illustrates incrementing from 0 to 1 to 2. The backward path illustrates decrementing from 3 to 2 to 1. In either direction, the update must be consistent with the loop's intended stopping point.

correct updateeventually reachesno effective updatechecks unchanged stateCondition trueiteration beginsUpdated positionmoves toward stopping pointSame positionvariable not updatedStopping pointloop can endCondition truerepeats indefinitely
How does control flow change when the loop condition remains true because the loop variable is not updated correctly?

Tracing a Complete Pass

Three Values, Two Loop Variables

Trace a generated loop that processes the values 5, 1, and 6. The counter starts at 0 and increases by 1 after each value. The accumulator starts at 0 and adds the current value after each value is processed.

Initialization: Before the first iteration, the counter is 0 and the accumulator is 0.

First iteration: The counter increases from 0 to 1. The accumulator adds 5, changing from 0 to 5.

Second iteration: The counter increases from 1 to 2. The accumulator adds 1, changing from 5 to 6.

Third iteration: The counter increases from 2 to 3. The accumulator adds 6, changing from 6 to 12.

After three iterations, the counter is 3 and the accumulator is 12.

process 5process 1process 6Startcounter 0, total 0Iteration 1counter 1, total 5Iteration 2counter 2, total 6Iteration 3counter 3, total 12
How do the loop variables change from initialization through three iterations?

Notice that the counter follows a fixed pattern: it increases once per iteration. The accumulator follows the values being processed: it increases by 5, then by 1, then by 6. This difference is the central diagnostic clue when tracing loop state.

Mistakes That Break Iteration

  • Using an uninitialized loop variable

    The loop variable has no defined starting state to trace.

    Fix: Initialize each variable before the loop begins.

  • Treating an accumulator like a counter

    Its final value represents a total of values rather than the number of events.

    Fix: Use a fixed increment for a counter and add processed values to an accumulator.

  • Forgetting the update

    The loop may continue checking the same state, so it may never reach its stopping point.

    Fix: Update the controlling variable on every required iteration.

  • Updating in the wrong direction

    The variable can move away from the stopping point and produce an infinite loop.

    Fix: Choose increment or decrement according to the direction needed for termination.

When debugging a loop, write a small state table with one row for initialization and one row for each iteration. Record the controlling position, the counter, and the accumulator. This makes missing updates, incorrect directions, and mistaken totals visible.

Practice the Trace

EASY

A generated loop processes the values 4, 2, and 7. Its counter begins at 0 and increases by 1 after each value. Its accumulator begins at 0 and adds the current value. Record the counter and accumulator after initialization and after each iteration.

Hints
  • Write the initial state before any value is processed.
  • Increase the counter by one for each of the three iterations.
  • Add 4, then 2, then 7 to the accumulator's previous total.

What do you think happens?

After all three generated values are processed, what are the counter and accumulator?

  • Counter 3 and accumulator 13
  • Counter 13 and accumulator 3
  • Counter 3 and accumulator 7
Reveal answer

Answer: Counter 3 and accumulator 13

The counter increases once for each of three iterations. The accumulator adds 4, 2, and 7, producing 13.

For a termination check, imagine that the same loop uses a position variable but never changes it. The position would remain at its initialized value. If the loop condition requires that position to move toward a stopping point, the unchanged state can cause the loop to continue indefinitely.

Reliable Loop Reasoning

  1. Iteration is the repeated execution of statements in a loop or recursive function.
  2. Initialization establishes the starting state before repetition begins.
  3. A counter tracks occurrences through fixed updates, while an accumulator builds a running total from processed values.
  4. Incrementing increases a variable by a fixed amount, and decrementing decreases it by a fixed amount.
  5. To avoid an infinite loop, verify that the controlling variable is initialized and updated in the correct direction toward the stopping point.

Key Takeaways

  • Trace iteration by recording initialization and every state update.
  • A counter counts events with a fixed increment, while an accumulator builds a total from varying values.
  • Increment and decrement operations move loop variables in different directions.
  • A loop risks becoming infinite when its controlling variable is uninitialized, unchanged, or moving away from the stopping point.