This may be a stupid question, but how does the efficiency of a while loop compare to that of a for loop? I\'ve always been taught that if you can use a for loop,
As you can guess from most of these answers, the main advantage of a for loop over a while loop is readability. A for loop is a lot cleaner and a lot nicer to look at. It's also much easier to get stuck in an infinite loop with a while loop. I would say that I agree with your teachings that if you can use a for loop, you should, so as long as you stick to that, your programming experiences will be much more enjoyable.
Think of the main difference as style: with a for
loop, you don't have to go looking for the initial value, threshold, and increment.
It's also a lot easier to make an infinite loop out of a while
because you forgot to increment.