Worked lessons

Why does my loop run one time too many?

Trace the index before reading each item. For a zero-indexed list of length n, the last valid index is n minus one.

Worked example

With five items, starting i at zero and continuing while i ≤ 5 produces indices 0, 1, 2, 3, 4 and 5. The sixth read fails. Change the condition to i < length and increase i once after each read. Make a trace with columns i, test and action.

Try it yourself

Test the repaired condition with an empty list and then one item. How many reads should take place?

Check your answer

For length zero, 0 < 0 is false and no read happens. For length one, index zero is read once. Testing just a long list could hide this boundary error.

Try a lesson tonight. Learn together.

Two minutes to set up. The first five-minute lesson is free, no card needed. Pick a subject your child has homework in.

Try the free lesson

Last checked . Tutorwell is an AI tutor, not a person, and it tells your child so.