4 loop statement, Loop statement – Rice Lake iRite IDE User Manual

Page 29

Advertising
background image

920i

Programming Reference - Language Syntax

25

To be the best by every measure

3.4.4

Loop Statement

END

LOOP

stmt-list

;

LOOP

optional-iteration-clause

Figure 3-15. Loop Statement Syntax

The loop statement is also quite important in programming. The loop statement is used to execute a statement list
0 or more times. An optional expression is evaluated and the statement list is executed. The expression is then
re-evaluated and as long as the expression is true the statements will continue to get executed. The loop
statement in

iRite

has three general forms. One way is to write a loop with no conditional expression. The loop

will keep executing the loop body (the statement list) until the exit statement is encountered. The exit statement
can be used in any loop, but is most often used in this version without a conditional expression to evaluate. It has
this form:

loop

<statement list>

end loop;

This version is most often used with an if statement at the end of the statement list. This way the statement list
will always execute at least once. This is referred to as a loop-until. Here is an example:

rGrossWeight : real;

loop

WriteLn(2, "I’m in a loop.");

GetGross(1, Primary, rGrossWeight);

if rGrossWeight > 200 then

exit;

end if;

end loop;

A similar version uses an optional while clause at the start of the loop. The while-loop version is used when you
want the loop to execute zero or more times. Since the expression is evaluated before the loop is entered, the
statement list may not get executed even once. Here is the general form for the while-loop statement:

while <expression>

loop

<statement list>

end loop;

Here is the same example from above, but with a while clause. Keep in mind that if the gross weight is greater
than 200 pounds, then the loop body will never execute:

rGrossWeight : real;

GetGross(1, Primary, rGrossWeight);

while rGrossWeight <= 200

loop

WriteLn(2, "I’m in a loop.");

GetGross(1, Primary, rGrossWeight);

end loop;

Here we see that we had to get the weight before we could evaluate the expression. In addition we have to get the
weight in the loop. In this example, it would be better programming to use the loop-until version.

Another version is known as the for-loop. The for-loop is best used when you want to execute a chunk of code
for a known or predetermined number of times. In its general form the for-loop looks like this:

Advertising
This manual is related to the following products: