Every new coder in my study group keeps writing for loops with the index starting at 1, and it breaks on the first array | Coding For Beginners - Vivisector
Every new coder in my study group keeps writing for loops with the index starting at 1, and it breaks on the first array
I watched 6 people in my Tuesday study group at the library downtown hit the same wall on the same exercise, and 5 of them had written for (int i = 1; i <= arr.length; i++). The array has 5 items, so they skip index 0 and then crash asking for index 5, and they blame the compiler instead of the loop. A simple rule fixes it: start at 0, use less than the length, and stop guessing. How do you explain this to someone without just saying "arrays are zero-indexed" and watching their eyes glaze over?
But here's the thing, telling them to "just start at 0" is what makes their eyes glaze over in the first place. I've had better luck showing them that the number isn't counting the items, it's the distance from the start. Picture a row of mailboxes where the first one is right at your feet, that first mailbox is zero steps away, not one. Once they see the number as "steps from the front" instead of "which item it is," the whole thing clicks. The fix isn't memorizing a rule, it's changing what they think the number even means.