For - do

Top  Previous  Next

A "for" loop is a powerful looping statement. It counts upward one at a time, and for each count it executes a block. The starting and ending values of the count are specified, and the count is stored in a variable so that it can be used by the block. This statement has the form:




For example:


        for Guess:= 1, 100 do TestGuess


Guess starts with a value of 1 and steps one at a time up to and including 100. TestGuess is executed 100 times.


In XPL0, the steps are always ascending, and the increment is always one. The loop control variable cannot be a real (or have a subscript). Negative loop limits can be used, but descending loops and other increments must be created using the other looping statements.


If the starting and ending limits are expressions, they are evaluated one time before the looping begins. The starting value is assigned to the control variable. This variable is compared to the ending limit before each pass through the loop. If it is greater, the loop is exited. Otherwise, the block is executed, and then the control variable is incremented.


Note that a "for" loop is not executed if the limits are not in ascending order, as in:


        X:= -10;

        for Guess:= 1, X do Text(0, "Way too low")


Also note that 32767 cannot be used as the ending limit because there is not a larger signed number that can be represented with 16 bits. Writing "for I:= 32000, 32767 do" is an infinite loop.