[Next] [Prev] [Right] [Left] [Up] [Index] [Root]
Iterative Statements

Iterative Statements

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.


Example Lang_break (H1E14)

> 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 89
Note 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


Example Lang_while (H1E15)

The following short program implements a run of the famous 3x + 1 problem on a random integer between 1 and 100.

> 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

Example Lang_repeat (H1E16)

This example is similar to the previous one, but it only prints x and the number of steps it takes before x becomes 1. We use a repeat loop, and illustrate that using a break it is not always necessary that the Boolean expression following the until ever evaluates to `true'. Similarly, a while true statement may be used if the user makes sure the loop will be exited using break.

> 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

[Next] [Prev] [Right] [Left] [Up] [Index] [Root]