Off-by-one Error - Looping Over Arrays

Looping Over Arrays

Consider an array of items, and items m through n (inclusive) are to be processed. How many items are there? An intuitive answer may be n−m, but that is off by one, exhibiting a fencepost error; the correct answer is n−m+1.

For this reason, ranges in computing are often represented by half-open intervals; the range from m to n (inclusive) is represented by the range from m (inclusive) to n+1 (exclusive) to avoid fencepost errors. For example, a loop that iterates five times can be written as a half-open interval from 0 to 5:

for (i = 0; i < 5; i++) { /* Body of the loop */ }

The loop body is executed first of all with i equal to 0; i then becomes 1, 2, 3, and finally 4 on successive iterations. At that point, i becomes 5, so i < 5 is false and the loop ends. However, if the comparison used were <= (less than or equal to), the loop would be carried out six times: i takes the values 0, 1, 2, 3, 4, and 5. Likewise, if i were initialized to 1 rather than 0, there would only be four iterations: i takes the values 1, 2, 3, and 4. Both of these alternatives can cause off-by-one errors.

Another such error can occur if a do-while loop is used in place of a while loop (or vice versa.) A do-while loop is guaranteed to run at least once.

Array-related confusion may also result from differences in programming languages. Numbering from 0 is most common, but some languages start array numbering with 1. Pascal has arrays with user-defined indices. This makes it possible to model the array indices after the problem domain.

Read more about this topic:  Off-by-one Error

Famous quotes containing the word looping:

    A book is like a man—clever and dull, brave and cowardly, beautiful and ugly. For every flowering thought there will be a page like a wet and mangy mongrel, and for every looping flight a tap on the wing and a reminder that wax cannot hold the feathers firm too near the sun.
    John Steinbeck (1902–1968)