Indeed, anything you can do using a for
loop can also be accomplished with a while
loop. The following two are equivalent:
for (initialCondition; test; nextStep) {
doSomething;
}
and
initialCondition;
while (test) {
doSomething;
nextStep;
}
So why do we have the for loop at all? There are two reasons.
First, the pattern in the second code snippet is very common (initialize something, then loop while updating on each step until a condition fails). Because it's so common, many language designers considered it worthwhile to have a special syntax for it.
Second, moving iteration variables (e.g. i
or j
) out of the loop body and inside the for
makes it easier for compilers and interpreters to detect certain classes of error (or perhaps even forbid them). For example, if I write (in MATLAB because I happen to have it open)
for i = 1:10
i = i + 5; // The body of
disp(i); // the loop.
end
then MATLAB presents me with a warning -- "Line 2: Loop index 'i' is changing inside a FOR loop"
. If I instead wrote it as a while
loop:
i = 1;
while i <= 10
i = i + 5; // The body of
disp(i); // the loop.
i = i + 1;
end
Uh-oh! Not only do I no longer get a warning from MATLAB, now my code is incorrect! Modifying the iteration variable in the body of the loop is dangerous, and it's rarely the case that you mean to do it. Writing "initialize, test, update" loops as for
loops rather than while
loops helps protect you from this class of error.