up previous next
For

loop command
Syntax

For I := N_1 To N_2 Do C EndFor
For I := N_1 To N_2 Step D Do C EndFor

where I is a dummy variable, N_1, N_2, and D are integer expressions,
and C is a sequence of commands.


Description
In the first form, the variable I is assigned the values N_1, N_1+1, ...,N_2 in succession. After each assignment, the command sequence C is executed. The second form is the same, except that I is assigned the values N_1, N_1+D, N_1+2D, etc. until the greatest value less than or equal to N_2 is reached. If N_2 < N_1, then C is not executed.

Note: Large values for N_1, N_2, or D are not permitted; typically they should lie in the range about -10^9 to +10^9.

Note: Don't forget the capitalization in the word To.

Example
  For N := 1 To 5 Do Print 2^N, " "; EndFor;
2 4 8 16 32
-------------------------------
  For N := 1 To 20 Step 3 Do Print N, " "; EndFor;
1 4 7 10 13 16 19
-------------------------------
  For N := 10 To 1 Step -2 Do Print N, " "; EndFor;
10 8 6 4 2
-------------------------------
  For N := 5 To 3 Do Print N, " "; EndFor;  -- no output
Loops can be nested.

Example
  Define Sort(Var(L))
    For I := 1 To Len(L)-1 Do
      M := I;
      For J := I+1 To Len(L) Do
        If L[J] < L[M] Then M := J EndIf;
      EndFor;
      If M <> I Then
        C := L[M];
        L[M] := L[I];
        L[I] := C
      EndIf;
    EndFor;
  EndDefine;

  M := [5,3,1,4,2];
  Sort(M);
  M;
[1, 2, 3, 4, 5]
-------------------------------
(Note that Var(L) is used so that the function can change the value of the variable referenced by L. See Var.)

See Also