2.2.8 Counting Iterations and Events

Overview

An iteration is one execution of a loop body. An event is an occurrence you choose to count inside that body. A loop may have five iterations while an event happens only twice. Keep a separate counter for the event so its value does not get confused with the loop index.

int[] counts = { 0, 2, 0, 3 };
int nonzeroDays = 0;
for (int i = 0; i < counts.Length; i++)
{
    if (counts[i] > 0)
        nonzeroDays++;
}
Separate Passes from Events
Activity diagram for counting iterations and events: separate passes from events.
Separate Passes from Events
  • New
  • Changed
  • Removed

The loop body runs four times, once per element. Only indexes 1 and 3 contain positive values, so nonzeroDays ends at 2. The final index value is not the event count.

The event counter starts at zero and changes only when its condition is true. If all entries are zero, traversal still runs four times while nonzeroDays stays zero.

Trace the Outcome

Trace i, counts[i], and nonzeroDays after each pass. State separately how many times the body ran and how many positive entries it found.