Every programmer makes these mistakes. The difference between a beginner and an experienced engineer is mostly that the experienced one expects them, and checks for them before they cause trouble. Here are the ones that bite most often with arrays.
An array of length n has indexes 0 to n - 1. Writing <= in the loop condition visits index n, which doesn't exist. What happens next depends on the language — and none of the outcomes are good:
undefined, and the bug surfaces later as NaN or a strange comparison.IndexError / ArrayIndexOutOfBoundsException — loud, but at least honest.Habit: when you write a loop bound or an index like i + 1, ask "what happens on the last element?" If you read nums[i + 1], the loop must stop at i < n - 1.
Free account
Sign up to read the rest of this lesson: 6 more sections, 1 drawing and code in JavaScript, Python, Java and C++.
Still to come