2.2.12 Off-by-One Errors

Find an Extra or Missing Soccer Round

The coach requests three recorded rounds, but the following loop records four. This is an off-by-one error: the body executes one time too many.

The defect is in the combination of the starting label and the comparison, not in the completion assignment.

Work Through the Soccer Example

This first example is intentionally incorrect for a three-round plan. Trace it before changing it.

Find an Extra or Missing Soccer Round
int completedRounds = 0;

for (int round = 0; round <= 3; round++)
{
    completedRounds = completedRounds + 1;
}
Follow the Values and Execution Order

List every label that passes the test

The loop starts at 0 and includes 3 because it uses <=. The successful labels are 0, 1, 2, and 3.

There are four labels in that list. Each successful test leads to one completion assignment, so the final count is 4.

Choose a matching start and boundary

Starting at 0 can correctly produce three passes when the condition is round < 3. The body then visits 0, 1, and 2.

Starting at 1 can also produce three passes when the condition is round <= 3. That version visits 1, 2, and 3.

Name the first, last, and failing label

For the one-based plan, the first label is 1, the last permitted label is 3, and the next label 4 must fail.

Writing these three values before coding helps you choose the comparison deliberately.

Check a one-round plan before trusting a larger one

With a start of 0 and the condition round <= 1, the body would visit 0 and 1: two passes for a one-round request. This small case makes the extra pass easy to see.

The same mismatch causes four passes for the three-round request. Testing a small plan helps you find the boundary defect before there are many intermediate values to track.

Trace This Example
Compare four start-and-boundary choices
Initial round Condition Labels that reach the body Body executions
0 round <= 3 0, 1, 2, 3 4; extra pass
0 round < 3 0, 1, 2 3
1 round <= 3 1, 2, 3 3
1 round < 3 1, 2 2; missing pass
Read the Matching Activity Diagram
Find an Extra or Missing Soccer Round.
Find an Extra or Missing Soccer Round
  • New
  • Changed
  • Removed

This diagram intentionally matches the faulty code. At its diamond, labels 0 through 3 all follow the true route. Each visit increases the completion count.

The exit occurs only at 4, after four completions. To model the zero-based correction, change the diamond to round < 3? so label 3 exits without a body action.

Try a Focused Change
Predict and Explain

Check your reasoning

Use for (int round = 0; round < 1; round++) for the zero-based version. It processes 0 and fails at 1.

Use for (int round = 1; round <= 1; round++) for the one-based version. It processes 1 and fails at 2. Each records exactly one completion.