Convert several while loops to for loops.

This is cleaner, reduces the scope of the iterator and avoids confusion.