next up previous contents
Next: if then statements Up: Simple exercises in MAGMA Previous: More complicated sets   Contents

for loops

There are basically two ``flavors'' of for loops, similar to the MAPLE for loops:

for i := <expression1> to <expression2> by <expression3> do
  <statements>
end for;

(if ``by <expression3> '' is omitted then it automatically increments by $+1$) and

for s in S do
  <statements>
end for;

For example,

> a:=0;                              
> for i:=1 to 3 do a:=i+a; end for;
> a;                               
6

and

> a:=0;    
> for i in [1..3] do a:=i+a; end for;
> a;
6
have the same effect.

Exercise 12   Construct a for loop over $i=1, ..., 20$ which appends $[i,{\tt NextPrime(i)}]$.

Remark 1   There is also case statement and a while loop but we shall not discuss these here.

In some cases, it appears that MAGMA wants you to type the ``for do'' statement on one line, the ``statements'' on the next line, and the ``end for'' on the last line. In other cases, having them all on one line is fine.



David Joyner 2001-08-22