Loop Boundaries and Off-by-One Errors

Part of: Iteration

The Most Common Loop Bug An off-by-one error happens when a loop runs one time too many or one time too few. It is the single most frequent loop mistake, and it almost always comes from the boundary of the loop, the start value and the comparison operator. Counting Iterations Precisely For a loop for (int i = a; i < b; i++), the body runs b - a times. For for (int i = a; i <= b; i++), it runs b - a + 1 times. The difference between < and <= changes the count by exactly one . Trace the First and Last Pass The reliable cure for off-by-one bugs is to trace by hand the first and last iterations: - What is the loop variable on the first pass? - What is it on the last pass that still satisfies the condition? - Does the body do the right thing at both ends? If you wrote i < n here, the loop would stop at 3 and miss the value 4, a classic off-by-one. Index Boundaries Boundaries matter even more with positions. Many structures use indices 0 to length - 1. Looping with i <= length (instead of i < length) reaches one past the end and causes an out-of-bounds error. Always match your boundary to whether the limit is inclusive or exclusive .

Challenge: Print Range Inclusive