CoCoA:For

From ApCoCoAWiki

For

loop command

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 <formula>-10^9</formula> to <formula>+10^9</formula>.

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

Example

  For N := 1 To 5 Do Print 2^N, <quotes> </quotes>; EndFor;
2 4 8 16 32
-------------------------------
  For N := 1 To 20 Step 3 Do Print N, <quotes> </quotes>; EndFor;
1 4 7 10 13 16 19
-------------------------------
  For N := 10 To 1 Step -2 Do Print N, <quotes> </quotes>; EndFor;
10 8 6 4 2
-------------------------------
  For N := 5 To 3 Do Print N, <quotes> </quotes>; 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] &lt; L[M] Then M := J EndIf;
      EndFor;
      If M &lt;&gt; 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.)

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.

Foreach

Repeat

While

   <type>programming</type>
   <type>loops</type>