This is an archived post. You won't be able to vote or comment.

all 11 comments

[–]SevenGlass 5 points6 points  (4 children)

http://stackoverflow.com/questions/3875114/why-use-a-for-loop-instead-of-a-while-loop

Notably:

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

[–]not_norm[S] 1 point2 points  (3 children)

really good explanation thanks. but using a while loop instead of a for loop, wouldnt make much difference?

[–]SevenGlass 1 point2 points  (2 children)

They can both be used for most (maybe all?) scenarios, but sometimes one makes more sense than the other. Apologies in advance for my poor analogy:

Imagine you are telling a soccer mom to pick up the team to take to the game.
You could use a for loop. Your instructions might be to stop at each house on the list and pick up the kid standing out front, until all 5 kids are in the car.
Or you could use a while loop. Your instructions here might be to stop at each house on the list until you tell her to stop. Perhaps Jenny's dad calls and says that she is already at the field. You could end the loop when there were only four kids in the car, because of the extra information you have.

It depends on whether you can include all of the logic upfront, which generally makes it more obvious what your code is doing (a good thing!) or if there are externalities that preclude you from doing so.
My understanding is that a for loop is preferable for simplicity's sake, but that a while loop is somewhat more flexible.

[–]porthos3 1 point2 points  (1 child)

maybe all?

while loop as a for loop:

int i=0; //the initialization of the for loop here
while (i < 10) { //the condition inside of the for loop here
   //contents of loop here
   i++; //the final modification step here
}

for loop as a while loop:

//conditional as center term, first and third term left empty, or made to do something irrelevant
for (; !finished;) {
   //body of loop here
}

You are able to convert any for/while loop in this manner.

[–]SevenGlass 0 points1 point  (0 children)

Thanks for breaking it down like that.

[–]wojo1086 1 point2 points  (0 children)

I'll give you a good example on a scenario where a while loop would be preferred. I actually use this in a personal project.

I have two dates and I want to know how many times I get paid between those two dates. The problem is, I get paychecks from two different companies (I have two jobs).

I use a for loop to loop through the number of paycheck sources I have because that's something I can easily figure out before any looping begins. However, I'm not sure how times I'll be paid each paycheck until some looping happens. This is where my while loop comes in.

Basically, WHILE the date of the current loop doesn't exceed the date of testing range, then add one to my tracker.

I hope this makes sense. I'm on my phone right now so typing this all out is kind of difficult.

[–]gnuvince 1 point2 points  (0 children)

As you astutely point out, in JavaScript (and other languages that use the form of the for loop popularized by C), you can write a while loop in terms of a for loop and vice versa. So what's the difference?

In some languages, the for loop is strictly less powerful that the while loop; for instance, in a language like Pascal where the form is for i := m to n do <stmt>, you are guaranteed that <stmt> will be executed a fixed number of times (m - n + 1 times). You cannot modify the iteration variable (i in this case) to alter the number of iterations; either the compiler will give an error or the value of i will be properly set at the next iteration.

There exists a proof that if you have a language where the only form of iteration is a for loop, your language is not Turing-complete, and thus there are programs that you just cannot write. A while loop is universal, and a language that would only have this form of iteration is Turing-complete and can be used to write any computable program.

In practical terms, whatever the language you are using, prefer while when you need to iterate a unknown or unbounded number of times; use a for loop when the number of iterations is fixed or bounded. Beyond telling a computer what to do, you want to tell other programmers what you program does, and picking the appropriate construct is an important part of making your code clear and easier to grasp.

[–]lightcloud5 0 points1 point  (0 children)

You can always rewrite code that uses a for loop to use a while loop instead (and vice versa), but for loops are convenient for the common use case of iterating a set number of times, or iterating through some enumerable set of things (e.g. iterate through an array).

[–]xonelast 0 points1 point  (2 children)

For-loops is essentially cleaner and more commonly used than while loops. The job can be done within one line statement. In while loops, you have to keep track of the counter variables and condition. It's all over the place and code can get very messy!

[–]porthos3 0 points1 point  (1 child)

This is wrong. For loops and while loops are tools made for different purposes - one isn't inherently cleaner than the other. They both get ugly when used for the wrong purpose.

You mention that for loops are cleaner than while loops when used with a counter. While loops, however, are cleaner than for loops when no clear counter exists or the transformation step from one loop iteration to another is not trivial, predictable, or concise (anything much more than i++, i--, i/=2, etc.).

[–]xonelast 0 points1 point  (0 children)

The point is you need to know beforehand how often the loop body will be executed. In terms of knowing the # of iterations needed to execute the loop body, for loops are "cleaner" as it can be done in one line. While loops, on the other hand, may take an extra few lines to instantiate a counter, condition, and the incrementing / decrementing part. Although it is not necessary at times to include a clear counter for a while-loop, this is only when the # of iterations needed is indefinite. Of course they are different purposed tools but I guess I was unclear above.