Andy Jack wrote:I looked at stack overflowand saw that we can use the while counter once while loop ends.
Cannot do that with for loop.
You can do that with a
for loop, you just need to declare the counter outside the loop. I actually look at it as an advantage the other way - a
for loop allows you to declare a counter where the scope is restricted to the loop. That's one reason why I'd use Stephan's approach when using an
Iterator. You can do it with a
while loop, and it's no more complicated. And you can argue that since you're not iterating for a fixed number of times a
while loop is more natural. But then you have to declare the
Iterator before the loop.
But generally, the most important difference is they express a different intent - fixed number of iterations vs. iterating till a condition occurs. And your code is generally easier to read if the intent expressed by the code matches what you're trying to achieve.