Why use a for loop instead of a while loop? [duplicate]

Possible Duplicates:
Iterate with for loop or while loop?
Loops in C - for() or while() - which is BEST?

When should one use a for loop instead of a while loop?

I think the following loops are identical, except for their syntax. If so, then why choose one over the other?

int i;
for (i = 0; i < arr.length; i++) {
  // do work
}

int i = 0;
while (i < arr.length) {
  // do work
  i++;
}

In your case, you don't gain much besides one less line of code in the for loop.

However, if you declare the loop like so:

for(int i = 0; i < x; i++)

You manage to keep i within the scope of the loop, instead of letting it escape to the rest of the code.

Also, in a while loop, you have the variable declaration, the condition, and the increment in 3 different places. With the for loop, it is all in one convenient, easy-to-read place.

Last thought:
One more important note. There is a semantic difference between the two. While loops, in general, are meant to have an indefinite number of iterations. (ie. until the file has been read..no matter how many lines are in it), and for loops should have a more definite number of iterations. (loop through all of the elements in a collection, which we can count based on the size of the collection.)


There is one reason to choose for over while: Readability.

By using a for loop, you're expressly saying your intent is to perform some type of operating that requires an initialization, a "step" operation, and a completion condition.

With while, on the other hand, you're only saying you need the completion condition.


I use 'while' when I don't necessarily need a counter, for example when you are reading from a file and you are waiting to reach EOF. In this case 'for' may not be the best alternative. When you are going through items on an array I'd rather use 'for' because it conveys intent better.


The one notable difference between a for() and while() loop is that a "continue" statement in a while() loop will branch to the top of the loop, while one in a for() loop will branch to the third part of the for() clause [the one after the condition, usually used to bump variables].


As a teacher I have been pondering this in various shapes and forms; my suggestion always boils down to

  • for-loops are for counting. counting up, counting down.
  • while / do-while constructs are for all other conditions. c!=EOF, diff<0.02, etc. Iterators/Enumerators are counters very suitable for for-loops.

i.e. your int=0; while( ... ) is hideous to my eyes.