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.
Yes, easily.
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.
The
while
loop and the classicalfor
loop are interchangable:While loop
does not have as much flexibility as afor loop
has and for loops are more readable than while loops. I would demonstrate my point with an example. A for loop can have form as:A while loop cannot be used like the above for loop and today most modern languages allow a
for each loop
as well.In my opinion, I could be biased please forgive for that, one should not use
while loop
as long as it is possible to write the same code withfor loop
.In C-like languages, you can declare for loops such as this:
In languages where
for
is more strict, infinite loops would be a case requiring awhile
loop.Using C
The basic premise is of the question is that
while
loop can be rewritten as afor
loop. Such asBeing rewritten as;
The question is predicated on the
init
andmodify
statements being moved into thefor
loop, and thefor
loop not merely being,But, it's a trick question. That's untrue because of internal flow control which
statements;
can include. From C Programming: A Modern Approach, 2nd Edition you can see an example on Page 119,This can not be rewritten as a
for
loop like,Why because "when
i
is equal to0
, the original loop doesn't incrementn
but the new loop does.And that essentially boils down to the catch,
Explicit flow control inside the
while
loop permits execution that afor
loop (with internalinit;
andmodify;
statements) can not recreate.