Common Off-By-One Errors in For Loops
Identify and prevent the notorious off-by-one error, the most common logical bug developers face when writing loops.
It is a logical bug where a loop boundary is miscalculated, causing the loop to execute one time too many or one time too few.
It relates to memory addressing. The index represents the memory offset from the starting position of the array. The first element has an offset of 0.
Always ensure your loop condition uses strictly less than (<) the array's length, rather than less than or equal to (<=).
Your code will run without crashing, but it will skip the final element, resulting in an incorrect output or a failed test case.
Dry-run your loop manually using a very small array (e.g., size 2). Check exactly what the counter values are on the first and last execution.
