For Loop - Equivalence With While Loops

Equivalence With While Loops

A for loop can be converted into an equivalent while loop by incrementing a counter variable directly. The following pseudocode illustrates this technique:

factorial = 1 for counter from 1 to 5 factorial = factorial * counter

is easily translated into the following while loop:

factorial = 1 counter = 1 while counter <= 5 factorial = factorial * counter counter = counter + 1

This translation is slightly complicated by languages which allow a statement to jump to the next iteration of the loop (such as the "continue" statement in C). These statements will typically implicitly increment the counter of a for loop, but not the equivalent while loop (since in the latter case the counter is not an integral part of the loop construct). Any translation will have to place all such statements within a block that increments the explicit counter before running the statement.

Read more about this topic:  For Loop

Famous quotes containing the word loops:

    An accurate charting of the American woman’s progress through history might look more like a corkscrew tilted slightly to one side, its loops inching closer to the line of freedom with the passage of time—but like a mathematical curve approaching infinity, never touching its goal. . . . Each time, the spiral turns her back just short of the finish line.
    Susan Faludi (20th century)