Appendix: While Loops

A While loop is a type of compound statement that begins with a conditional expression. As long as this expression evaluates to True, the code block associated with the loop will repeat indefinitely. This lets you create expressions that can run once, multiple times or not at all, depending on whether the predicate condition is satisfied.

While loops are written as follows:




The Expression is a single-line conditional expression which, if evaluated as True, will cause the code written between the brackets to be executed. This code can be either a single- or multi-line expression, where each line ends in a semi-colon.

When execution of the nested code has concluded, the conditional expression will be evaluated again and, if it is still True, the loop will be executed once more. This process continues until it no longer evaluates as True, at which point the loop ends.

It is critically important for the loop to be written so that it will eventually cause the conditional expression to evaluate as False, ending the loop. Without this the loop will run indefinitely, causing your application to halt and require its manual termination.

A simple example of a well-constructed While loop, whose consequent will eventually cause the loop to end, is shown below:

While:(NumberOfSweets < 10)
NumberOfSweets:= NumberOfSweets + 1;

Regardless of the initial value of the NumberOfSweets variable, adding 1 each time will eventually cause that value to reach 10, ending the loop. If the value of NumberOfSweets is 10 or more before the loop is initialised, the predicate will immediately evaluate to False and as a result, the consequent would never be executed.

If you cannot be certain that your nested code will cause the conditional expression to eventually evaluate to False, you should use a counter or some other hard limit to ensure the loop cannot run more than a specific number of times.