Why use a for loop instead of a while loop?

Ziggy picture Ziggy · Oct 6, 2010 · Viewed 56k times · Source

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++;
}

Answer

jjnguy picture jjnguy · Oct 6, 2010

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.)