The repeat-until Loop


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

image from book
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.
image from book

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).

image from book
Figure 4-5: An erroneous repeat-until loop

Listing 4-10: An erroneous repeat-until loop

image from book
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.
image from book

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.



Inside Delphi 2006
Inside Delphi 2006 (Wordware Delphi Developers Library)
ISBN: 1598220039
EAN: 2147483647
Year: 2004
Pages: 212
Authors: Ivan Hladni

Similar book on Amazon

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net