Loops
Prior | Next
ESPL has three statements that execute blocks of code repeatedly:
- The repeat statement
- The while statement
- The for statement
Repeat Statement
The repeat statement repeats a statement or series of statements until
some condition is True. The statement begins with the repeat
reserved word and ends with the reserved word until, followed by the
condition that is evaluated. The condition is always a Boolean expression.
Example:
var
i: integer;
begin
i := 0;
repeat
i := i + 1;
writeln( i );
until i = 10;
end;
When this script is run, the numbers 1 through 10 are written down the
edge of the Output window. The Boolean expression i = 10 isn't
evaluated until the end of the repeat..until block. This means that the
statements within the repeat..until block always run at least one time.
While Statement
While the repeat statement evaluates a condition at the end of the
loop, the while statement evaluates a condition at the beginning of the
loop. It starts with the while reserved word and the tested condition,
which must always be a Boolean expression. If the condition is met (the
expression is True), the code in the while statement runs until it
reaches the end of the statement and the expression is tested again. As soon as
the expression is False, the while statement stops running, and
execution continues after the while loop.
This example of a while loop uses the same example as the repeat
loop did:
var
j: integer;
begin
j := 0;
while j < 10 do begin
j := j + 1;
writeln( j );
end;
end;
When this script is run, the following Boolean expression is examined first: j
< 10. If it is True, the remainder of the code within the while
statement runs, and then the expression is evaluated again. If the
expression is False, the while statement stops running.
FOR Loop
A for loop is ideal when you need to repeat an action a predetermined
number of times. A control variable is assigned an initial value and
iterated until the ending value is reached. The statement contained by the
for statement is executed once for every value in the range initial
value to final value. Example:
for j := InitialValue to FinalValue do DoSomething;
Prior | Next
|