Three types of iterative statement are provided in Magma: the {tt for}-statement providing definite iteration and the while- and repeat-statements providing indefinite iteration.
Iteration may be performed over an arithmetic progression of integers or over any finite enumerated structure. Iterative statements may be nested. If nested iterations occur over the same enumerated structure, abbreviations such as for x, y in X do may be used; the leftmost identifier will correspond to the outermost loop, etc. (For nested iteration in sequence constructors, see Chapter number chapSeq.)
Early termination of the body of loop may be specified through use of the `jump' commands break and continue.
The expressions in this for loop must return integer values, say b, e and s (for `begin', `end' and `step') respectively. The loop is ignored if either s>0 and b>e, or s<0 and b<e. If s=0 an error occurs. In the remaining cases, the value b + k.s will be assigned to i, and the statements executed, for k=0, 1, 2, ... in succession, as long as b + k.s< e (for e>0) or b + k.s>e (for e<0).If the required step size is 1, the above may be abbreviated to:
Each of the elements of the finite enumerated structure S will be assigned to x in succession, and each time the statements will be executed.
Check whether or not the Boolean expression has the value `true'; if it has, execute the statements. Repeat this until the expression assumes the value `false', in which case statements following the end while; will be executed.
> x := Random(1, 100); > while x gt 1 do > x; > if IsEven(x) then > x div:= 2; > else > x := 3*x+1; > end if; > end while; 13 40 20 10 5 16 8 4 2
Execute the statements, then check whether or not the Boolean expression has the value `true'. Repeat this until the expression assumes the value `false', in which case the loop is exited, and statements following it will be executed.
> x := Random(1, 1000); > x; 172 > i := 0; > repeat > while IsEven(x) do > i +:= 1; > x div:= 2; > end while; > if x eq 1 then > break; > end if; > x := 3*x+1; > i +:= 1; > until false; > i; 31
> p := 10037; > for x in [1..100] do > for y in [1..100] do > if x^2+y^2 eq p then > print x, y; > break x; > end if; > end for; > end for; 46 89Note that break instead of break x would have broken only out of the inner loop; the output in that case would have been:
46 89 89 46