The while Loop


The while and repeat-until loops are different from the for loop because they don't use an iteration variable to perform the iteration. Unlike the for loop, which iterates a specific number of times, the while and repeat-until loops are used when we don't know how many times to perform the iteration.

Both while and repeat-until loops use a condition to determine how many times to perform the iteration. In essence, the while loop continues to execute statements while the condition is True. The syntax of the while loop is:

while condition do    statement;

When working with the while loop, you have to remember to modify the condition inside the loop or else the loop will continue executing forever and the application will become unresponsive. When this happens, the user will probably have to terminate the task (on an NT/2000/XP-based computer) or restart the computer (Windows 95/98/ME).

Let's start with an example that simply displays a couple of numbers and doesn't hang the computer.

Listing 4-8: A simple while loop

image from book
program Project1; {$APPTYPE CONSOLE} uses   SysUtils; var   i: Integer; begin   i := 1;   { Display numbers 1 to 10. }   while i <= 10 do   begin     WriteLn(i);     i := i + 1;   end;   ReadLn; end.
image from book

The while loop tests the condition before it starts executing statements in the loop block. If the condition evaluates to False at the beginning, the while loop will not execute at all. You can test this by simply setting the i variable to 11 or any other value larger than 10.

If the condition evaluates to True, the while loop executes all statements in the block. Once it has finished executing the statements in the block, the loop reevaluates the condition to see if it should iterate again. If the condition evaluates to True, the loop is continued until it finally evaluates to False. If the condition evaluates to False, the loop terminates.



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