AP® Computer Science A glossary
Off by one error
Also called: off-by-one error
Course: AP® Computer Science A Shows up in: Unit 2: Selection and Iteration
An error in which a loop runs one time too many or one time too few, often from < versus <= or a wrong starting value.
Appears in the course and exam description (CED): 2.7.A.4
Check every loop by tracing its first and last iteration. In string loops, an off by one error often throws a StringIndexOutOfBoundsException.
for (int lap = 1; lap < 5; lap++) { // meant to print 1 to 5
System.out.print(lap + " ");
}
Output:
1 2 3 4 Learn it properly, with a checkpoint 2.7 while Loops