Inside Delphi 2006 (Wordware Delphi Developers Library)
The repeat-until loop, like the while loop, uses a condition to determine the number of times it needs to execute a group of statements. One difference between the while and repeat-until loops is that the while loop executes statements while the condition is True, and the repeat-until loop executes statements while the condition is False (until the condition is met).
The syntax of the repeat-until loop is:
repeat statement_1; statement_n; until condition;
Let's see how to display the numbers 1 to 10 using the repeat-until loop.
Listing 4-9: A simple repeat-until loop
program Project1; {$APPTYPE CONSOLE} uses SysUtils; var i: Integer; begin i := 1; { Display numbers 1 to 10. } repeat WriteLn(i); i := i + 1; until i > 10; ReadLn; end.
Another major difference between the while and repeat-until loops is that the repeat-until loop tests the condition after it executes the statements in the block. This means that the repeat-until loop executes the statements at least once, regardless of the condition. This can lead to subtle errors in your applications (see Listing 4-10 and Figure 4-5).
Listing 4-10: An erroneous repeat-until loop
program Project1; {$APPTYPE CONSOLE} uses SysUtils; var i: Integer; begin i := 25; repeat WriteLn('Number ', i, ' is smaller than number 10.'); i := i + 1; until i >= 10; ReadLn; end.
Unlike other loop constructs, the repeat-until loop acts as a block, so you can automatically write a larger number of statements inside the repeat-until loop without having to define a block.