Computer Science
Off-by-One Loop Error
Students write a loop that runs one time too many or one time too few when counting array indices.
Quick check
Why students make it
They mix up the number of items with the last valid index. In zero-based arrays, an array with n items has last index n - 1.
The rule done right
For an array of length n with zero-based indexing, valid indices are . To visit every element once, start at 0 and continue while i < n.
Related resources
- Programming Fundamentals Cheat Sheet
- Data Structures Overview Cheat Sheet
- Algorithms & Big-O Notation Cheat Sheet
- Two Pointers & Sliding Window Patterns Cheat Sheet
- CS, Loops and Control Flow Worksheet
- CS, Arrays and Lists Worksheet
- CS, Sorting Algorithms, Bubble, Selection, and Insertion Worksheet
- Java Array & ArrayList Explorer Tool
- Debugging & Unit Testing Explorer Tool
- Sorting Algorithm Visualizer Tool
- Loops & Pattern Coder Tool
- Selection & Iteration Code Tracing Lab Lab
- Selection & Iteration Lab Lab
- Arrays & ArrayList Lab Lab
- Debugging & Unit Testing Lab Lab
- Loops, Debugging & Animation Lab Lab
Continue learning
- Infinite Loop from a Missing UpdateCommon mistake
- Confusing Assignment with ComparisonCommon mistake
- Coding Theory & Error DetectionCheat sheet
- Error Propagation and Uncertainty Calculations ReferenceCheat sheet
- Calculus, Sensitivity and Error PropagationStudy poster
- Calculus, Tangent Line Approximation ErrorStudy poster