Up | Next | Prev | PrevTail | Tail |
The for
… do
feature allows easy coding of a repeated operation in which the number
of repetitions is known in advance. If the criterion for repetition is more complicated,
while
… do
can often be used. Its syntax is:
while
\(\langle \)boolean expression\(\rangle \) do
\(\langle \)statement\(\rangle \)The while
… do
controls the single statement following do
. If several statements are to
be repeated, as is almost always the case, they must be grouped using the <
<
… >
>
or
begin
… end
as in the example below.
The while
condition is tested each time before the action following the do
is attempted.
If the condition is false to begin with, the action is not performed at all. Make sure that
what is to be tested has an appropriate value initially.
Example:
Suppose we want to add up a series of terms, generated one by one, until we reach a term which is less than 1/1000 in value. For our simple example, let us suppose the first term equals 1 and each term is obtained from the one before by taking one third of it and adding one third its square. We would write:
ex:=0; term:=1; while num(term - 1/1000) >= 0 do <<ex := ex+term; term:=(term + term^2)/3>>; ex;
As long as term
is greater than or equal to (>=
) 1/1000 it will be added to ex
and the
next term
calculated. As soon as term
becomes less than 1/1000 the while
test fails
and the term
will not be added.
Up | Next | Prev | PrevTail | Front |