views:

642

answers:

4

I know a while loop can do anything a for loop can, but can a for loop do anything a while loop can?

Please provide an example.

+14  A: 

Yes, easily.

while (cond) S;

for(;cond;) S;
Adam Wright
I may as well add that this applies in C, C++, Java, C# and probably plenty of other languages that borrow heavily from C, but does not apply in e.g. Pascal.
Steve314
What I like about this answer is that it simultaneously demonstrates that it can be done, and why it's a pointless thing to do.
Adam Luchjenbroers
A: 

In C-like languages, you can declare for loops such as this:

for(; true;)
{
    if(someCondition)
       break;
}

In languages where for is more well defined, infinite loops would be a case requiring a while loop.

Stuart Branham
+2  A: 

The while loop and the classical for loop are interchangable:

for (initializer; loop-test; counting-expression) {
    …
}

initializer
while (loop-test) {
    …
    counting-expression
}
Gumbo
+1  A: 

If you have a fixed bound and step and do not allow modification of the loop variable in the loop's body, then for loops correspond to primitive recursive functions.

From a theoretical viewpoint these are weaker than general while loops, for example you can't compute the Ackermann function only with such for loops.

If you can provide an upper bound for the condition in a while loop to become true you can convert it to a for loop. This shows that in a practical sense there is no difference, as you can easily provide an astronomically high bound, say longer than the life of the universe.

starblue