Off by one errors



         


An off-by-one error in computer programming is an avoidable error in which a loop iterates one too many or one too few times than desired. Usually this problem arises when a programmer fails to take into account that a sequence starts at zero rather than one, or makes mistakes such as using "is less than" where "is less than or equal to" should have been used in a comparison.

For example, in the C programming language, a loop that iterates five times would be written as follows:

for(int 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 repeated 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 are off-by-one errors.

Another such error can occur if the difference between a "do-while" and a "while" loop in C programming is not familiarized. The former is guaranteed to run at least once.

Off-by-one errors are a frequent source of bugs in computer software.

See also Fencepost error.





  View Live Article   This article is from Wikipedia. All text is available under the terms of the GNU Free Documentation License