next up previous contents
Next: Recursive Calls Up: Iteration Previous: The for Command

The while Statement

The syntax of the while command in Darwin is as follows

		while conditional boolean expression do

{ break }
{ next }

The while loop executes until the conditional boolean expression evaluates to false or it encounters a break command within the body of the loop. If it encounters a next command within the body of the loop, then the conditional boolean expression is evaluated immediately and if it still evaluates to true, the body is executed again starting at the beginning.

> i:=0:
> while (i<5) do
>   i:=i+1:                      # increment i
>   if (i=3) then next; fi;
>   lprint(i);                   
> od:

> while (true<>false) do         # an empty infinite loop
>   if true then break  fi;      # or is it?
> od;

> i:=1:
> while (true) do                # only way out is a break statement now
>   lprint(i);
>   if (i=10) then break; fi;    # a way to execute from a while loop
>   i:=i+1:                      # at any point in the body
> od:

We could exit a while loop via a return command (§[*] of Chapter [*]) if the loop appears in a procedure. Remember, however, that the return exits the current procedure. The break command only exits the loop.

> HarshBreakup := proc( )
>   i:=1;
>   while (i < 4) do
>     if (i=3) then
>       return();
>     fi;
>     i:=i + 1;
>   od;
>   print('The very last line');
> end:

> HarshBreakup();
<no output is generated>

Gaston Gonnet