Incremental Java
Loop Equivalence

Which Loop is More Powerful?

Is a for loop more powerful than a while loop? How about a do while loop? Perhaps they are all the same? What does it mean to say one loop is more powerful than another?

We can say two loop constructs are equally powerful if you can write one in terms of the other.

for loop as powerful as a while

We can rewrite a while loop as a for loop, showing a for can do everything a while loop can.

Here's the syntax for a while loop.

while ( cond )
   while body
This is easily rewritten as a for loop.
for ( ; cond ; )
   while body
To emulate the while loop: If you trace the code with an example, you see they behave the same.

while loop as powerful as a for

We can also emulate a for loop using a while loop. Here's the syntax for a for loop.
for ( init ; cond ; update )
   for body
Think about what it takes to emulate this using a while loop.
init ;
while ( cond )
{
   for body
   update 
}
This is almost equivalent to a for loop. The only time it isn't is if the for body has a continue statement.

If it were in a for loop, the continue statement would jump to the update. However, when translated to while loop, it jumps to the condition.

break statements are fine in for bodies, since they exit the loop. They also exit the loop when they are in the while body.

Find a simple for loop example. Translate it to a while loop as shown above, and see if the two behave the same.

while loop as powerful as a do while

We can write a do while loop using a while loop. It's awkward, but it can be done.

Recall the syntax of the do while loop.

do
   do-while body
while ( cond ) ;
Recall that a do while loop executes the do-while body at least once. A while loop may not execute any iterations.

To force at least one iteration of the loop body, we copy it.

do-while body
while ( cond )
   do-while body
This translation doesn't work if there's a break in the do-while body. In fact, it won't compile since break must appear in a loop. The translation also doesn't work if there's a continue statement in the do-while body for the same reason.

Three More To Go

Try doing the following: Consider the effects of break and continue in the loop bodies.