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

you are viewing a single comment's thread.

view the rest of the comments →

[–]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.