DO…LOOP
Description
A control structure that is a general-purpose iteration statement
used to execute a block of statements while or until a condition is
true.
DO… LOOP has four formats:
-
DO WHILE
Executes a block of statements while the specified condition is
true. The loop ends when the condition becomes false. If the condition
is false on the first evaluation, the statement block does not
execute. -
LOOP UNTIL
Executes a block of statements at least once and continues until
the specified condition is true. -
LOOP WHILE
Executes a block of statements at least once and continues while
the specified condition is true. The loop ends when the condition
becomes false.In all four formats of the DO…LOOP control structure, DO marks
the beginning of the statement block that you want to repeat. The
LOOP statement marks the end.
You can nest DO…LOOP control structures.
Syntax
|
1 2 3 4 5 6 7 8 9 10 11 12 |
DO UNTIL condition statementblock LOOP DO WHILE condition statementblock LOOP DO statementblock LOOP UNTIL condition DO statementblock LOOP WHILE condition |
|
Parameter |
Description |
|---|---|
|
condition |
The condition you are testing |
|
statementblock |
The block of statements you want to |
Usage
Use DO WHILE or DO UNTIL when you want to execute a block of
statements only if a condition is true (for WHILE) or false (for UNTIL).
DO WHILE and DO UNTIL test the condition before executing the block of
statements.
Use LOOP WHILE or LOOP UNTIL when you want to execute a block of
statements at least once. LOOP WHILE and LOOP UNTIL test the condition
after the block of statements has been executed.
Examples
DO UNTIL
The following DO UNTIL repeatedly executes the Beep function until A
is greater than 15:
|
1 2 3 4 5 |
integer A = 1, B = 1 DO UNTIL A > 15 Beep(A) A = (A + 1) * B LOOP |
DO WHILE
The following DO WHILE repeatedly executes the Beep function only
while A is less than or equal to 15:
|
1 2 3 4 5 |
integer A = 1, B = 1 DO WHILE A <= 15 Beep(A) A = (A + 1) * B LOOP |
LOOP UNTIL
The following LOOP UNTIL executes the Beep function and then
continues to execute the function until A is greater than 1:
|
1 2 3 4 5 |
integer A = 1, B = 1 DO Beep(A) A = (A + 1) * B LOOP UNTIL A > 15 |
LOOP WHILE
The following LOOP WHILE repeatedly executes the Beep function while
A is less than or equal to 15:
|
1 2 3 4 5 |
integer A = 1, B = 1 DO Beep(A) A = (A + 1) * B LOOP WHILE A <= 15 |