Use a different counter for counting and iterating

Some values may be undefined, resulting in an infinite loop.