Go to the Next or Previous section, the Detailed Contents, or the Amiga E Encyclopedia.

4.2.2`WHILE` loop

The `FOR` loop used a loop variable and checked whether that variable had gone past its limit. A `WHILE` loop allows you to specify your own loop check. For instance, this program does the same as the program in the previous section:

```PROC main()
DEF x
x:=1
WHILE x<=100
WriteF('\d ', x)
x:=x+1
ENDWHILE
WriteF('\n')
ENDPROC
```

We've replaced the `FOR` loop with an initialisation of `x` and a `WHILE` loop with an extra statement to increment `x`. We can now see the inner workings of the `FOR` loop and, in fact, this is exactly how the `FOR` loop works.

It is important to know that our check, `x<=100`, is done before the loop statements are executed. This means that the loop statements might not even be executed once. For instance, if we'd made the check `x>=100` it would be false at the beginning of the loop (since `x` is initialised to one in the assignment before the loop). Therefore, the loop would have terminated immediately and execution would pass straight to the statements after the `ENDWHILE`.

Here's a more complicated example:

```PROC main()
DEF x,y
x:=1
y:=2
WHILE (x<10) AND (y<10)
WriteF('x is \d and y is \d\n', x, y)
x:=x+2
y:=y+2
ENDWHILE
ENDPROC
```

We've used two (local) variables this time. As soon as one of them is ten or more the loop is terminated. A bit of inspection of the code reveals that `x` is initialised to one, and keeps having two added to it. It will, therefore, always be an odd number. Similarly, `y` will always be even. The `WHILE` check shows that it won't print any numbers which are greater than or equal to ten. From this and the fact that `x` starts at one and `y` at two we can decide that the last pair of numbers will be seven and eight. Run the program to confirm this. It should produce the following output:

```x is 1 and y is 2
x is 3 and y is 4
x is 5 and y is 6
x is 7 and y is 8
```

Like the `FOR` loop, there is a horizontal form of the `WHILE` loop:

```  WHILE expression DO statement
```

Loop termination is always a big problem. `FOR` loops are guaranteed to eventually reach their limit (if you don't mess with the loop variable, that is). However, `WHILE` loops (and all other loops) may go on forever and never terminate. For example, if the loop check were `1<2` it would always be true and nothing the loop could do would prevent it being true! You must therefore take care that your loops terminate in some way if you want to program to finish. There is a sneaky way of terminating loops using the `JUMP` statement, but we'll ignore that for now.

Go to the Next or Previous section, the Detailed Contents, or the Amiga E Encyclopedia.