Format:
do [[varying] var = expression] while/until condition [by expression]
statements;
enddo;
[ ] indicates that this part is optional.
Description:
The do statement executes one or more statements repeatedly, in a loop, either while a logical condition is true, or until a logical condition is no longer true. The do and enddo keywords are required. You must use a while or until phrase to terminate the loop. The condition is evaluated on each repetition of the loop before any of the statements within the loop are executed.
When the while option is used, it means the statements within the loop (between do and enddo) are executed while the condition remains true. That is, if the condition is true, the statements are executed. If the condition becomes false, execution moves to the first statement following the enddo keyword.
When the until option is used, the statements within the do are executed until the condition becomes true. That is, if the condition is false the statements are executed. If the condition becomes true, execution moves to the first statement following the enddo keyword.
The by phase adds the indicated number or numeric expression (expression) to the variable after each repetition of the loop. If the by phrase is present, at the end of each repetition of the loop, the expression is evaluated. The result of the expression is added to the numeric variable in the varying clause. If the by phrase is omitted, 1 is added to the variable at the end of each repetition of the loop. For example, if you wanted to process only odd-numbered records, you could increment your loop by 2.
In the varying clause, the variable must be a numeric variable. The variable assignment is performed once, before the first repetition of the loop. The varying keyword has no effect on the command, and so may be omitted. It is possible to declare a numeric variable after the varying keyword, in which case the numeric variable's scope is the duration of the do loop.
You can exit the loop early by using break and you can continue execution with the next iteration of the loop by using next.
Example:
HEAD = 0;
do varying i = 1 until HEAD > 0 or i > totocc(PERSON)
if RELATIONSHIP(i) = 1 then
HEAD = i;
endif;
enddo;
This same example could be rewritten using the while condition as follows:
HEAD = 0;
do varying i = 1 while HEAD = 0 and i <= totocc(PERSON)
if RELATIONSHIP(i) = 1 then
HEAD = i;
endif;
enddo;
It is purely a matter of preference as to which method should be used.
See also: For Statement, While Statement, If Statement