There exist three types of iterative loop in Magma: the conditional while and repeat loops, and the for loop. Within loops a special prompt will appear, indicating that the loop has yet to be closed.
Iteration can 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 like for x, y in X do can be used; the leftmost identifier will correspond to the outermost loop, etc. (For nested iteration in sequence constructors, see Chapter 8).
For each of the loops the `jump' commands break and continue exist.
> 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
> x := Random(1, 100); > while x gt 1 do > print 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
> x := Random(1, 1000); > print 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; > print i; 31