7.10. For Statements

The for-statement provides a means of executing repeatedly a given statement, the "controlled statement", for different values of a chosen variable, which may (or may not) occur within the controlled statement. A typical form of for-statement is


FOR i := 1 STEP 1 UNTIL 4,
    6 STEP 2 UNTIL 10,
    15 STEP 5 UNTIL 30
    DO Statement

Other forms are exemplified by


FOR i := 1, 2, 4, 7, 15 DO Statement

which is self-explanatory, and


FOR i := i + 1 WHILE x < y DO Statement

In the latter example, the clause "i + 1 WHILE x < y" counts as a single for-element and could be used as one element in a list of for-elements (the "for-list"). As each for-element is exhausted, the next element in the list is taken. The syntax is

Forstatement ::= 
     FOR  Wordreference :=  Forlist  DO Statement 

Forlist ::= 
     Forelement
     Forelement ,  Forlist 

Forelement ::= 
     Expression
     Expression  WHILE Condition
     Expression  STEP  Expression  UNTIL  Expression 

The controlled variable is a word reference, i.e. either an anonymous reference or a declared word reference.

7.10.1. For-elements with STEP

Let the element be denoted by


e1 STEP e1 UNTIL e3

In contrast to Algol 60, the expressions are evaluated only once. Let their values be denoted by v1, v2 and v3 respectively. Then

  1. v1 is assigned to the control variable,

  2. v1 is compared with v3. If (v1 - v3) * v2 > 0, then the for-element is exhausted, otherwise

  3. the controlled statement is executed,

  4. the value of v1 is set from the controlled variable, then incremented by v2 and the cycle is repeated from (a).

7.10.2. For-elements with WHILE

Let the element be denoted by


e1 WHILE Condition

Then the sequence of operation is

  1. e1 is evaluated and assigned to the control variable,

  2. the condition is tested. If false, the for-statement is exhausted, otherwise

  3. the controlled statement is executed and the cycle repeated from (i).

Unlike those in Section 7.10.1, the expression e1 and those occurring in the condition are evaluated repeatedly.