2.4.16 Counting Events in a Loop

Count Checked Rounds and Active Rounds Separately

The Wildcats schedule four rounds, but round 2 is a rest round. The application needs both the number of rounds checked and the number that count as active.

One body pass does not necessarily mean one active event. Use separate counters for the two questions.

Work Through the Soccer Example

The statements below belong inside an existing method. The round label controls traversal; the other two values record results.

Count Checked Rounds and Active Rounds Separately
int round = 1;
int roundsChecked = 0;
int activeRounds = 0;

while (round <= 4)
{
    roundsChecked = roundsChecked + 1;

    if (round != 2)
    {
        activeRounds = activeRounds + 1;
    }

    round++;
}
Follow the Values and Execution Order

Give each variable one job

The local round identifies the current scheduled round. roundsChecked counts all completed body passes, while activeRounds counts only those that meet the active-round condition.

The update round++; adds one to the label, moving to the next scheduled round.

Check every scheduled round

The assignment to roundsChecked is outside the if, so it executes on every pass. The rest round is still a scheduled round that must be examined.

Increase the event count conditionally

For round 2, round != 2 is false and the active counter does not change. For rounds 1, 3, and 4, that comparison is true and one active round is recorded.

The four passes therefore produce only three active events.

Explain the final values separately

After round 4, the next label is 5 and the condition is false. roundsChecked is 4 and activeRounds is 3.

The label 5 identifies the failed candidate; it is not the number of checked or active rounds.

Keep a rest round in the traversal

The coach scheduled round 2 even though it is not active. The loop must examine it, decide not to increase activeRounds, and then move to round 3.

Skipping an event-counter update is not the same as skipping the rest of the body. The roundsChecked update and the progression to the next label still belong to that pass.

Trace This Example
Worked soccer trace
Round visited Active condition roundsChecked after pass activeRounds after pass
1 True 1 1
2 False 2 1
3 True 3 2
4 True 4 3
5; exit test No body 4 3
Read the Matching Diagram
Count Checked Rounds and Active Rounds Separately.
Count Checked Rounds and Active Rounds Separately
  • New
  • Changed
  • Removed

The first count assignment lies on every true loop route. The second is inside its own decision and can be skipped. Both alternatives rejoin before round++, so every scheduled round advances to the next label.

Try a Focused Change
Predict and Explain

Check your reasoning

All four rounds are still checked, so roundsChecked is 4. Only rounds 3 and 4 are active, so activeRounds is 2. The next label is still 5, where the while condition becomes false.