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.
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.
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.
The while
loop and the classical for
loop are interchangable:
for (initializer; loop-test; counting-expression) {
…
}
initializer
while (loop-test) {
…
counting-expression
}
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.