What is exactly the off-by-one errors in the while loop?how do i figure it out and how to fix it? Thanks
+2
A:
An off-by-one error is for example when you write intend to perform a loop n times and write something like:
for (int i = 1; i < n; ++i) { ... }
or:
for (int i = 0; i <= n; ++i) { ... }
In the first case the loop will be executed (n - 1) times and in the second case (n + 1) times, giving the name off-by-one. Other variations are possible but in general the loop is executed one too many or one too few times due to an error in the initial value of the loop variable or in the end condition of the loop.
The loop can be written correctly as:
for (int i = 0; i < n; ++i) { ... }
A for loop is just a special case of a while loop. The same kind of error can be made in while loops.
Mark Byers
2010-05-30 19:01:05
hey, your examples are off by 2 ;)
Agos
2010-05-30 19:28:45