Loops are used to execute a sequence of instructions repeatedly. In order to exit from a loop, we must have a method for checking to see if we have completed our task. To show this graphically, we can use a device called a flow chart.
There are two basic kinds of loops, one which can be exited at the beginning and one which can be exited at the end. With the one which can be exited at the beginning, the other statements in the loop may never be exectued. With the one which can be exited at the end, the statements in the loop will be executed at least once.
This basic sort of loop requires that the statements inside the loop will be executed at least once. This loop has the feature that the exit-condition check is executed at the end of the loop.
% Print the first five Natural numbers num := 1 loop put num num := num + 1 exit when num > 5 end loop
Before the loop is begun, the counter called num is initialized to the first value desired. The loop itself consists of five lines:
Just before the end of each iteration of the statements inside the loop, the condition is checked. If the condition is TRUE, the loop is exited. N.B. The statements inside the loop will ALWAYS be executed at least once, because the condition is not checked until after the statements have been executed.
An alternative sort of loop checks the exit condition at the beginning of the loop. This kind loop allows the code in the loop to be skipped completely if desired.
% Print the first five Natural numbers num := 1 loop exit when num >= 5 put num num := num + 1 end loop
Here, before the loop is begun, the counter called num is initialized to the first value desired. (This will ensure that the code inside the loop will be executed.) The loop itself consists of five lines:
At the start of each iteration of the statements inside the loop, the condition is checked. Only if the condition is FALSE are the remaining statements executed. N.B. This means that the statements inside the loop will NOT be executed even once if the exit condition is TRUE when the initial check is made.
Although these two kinds of loops have been used to perform the same task here, they are usually used differently.
The end-exit loop is typically used when you must do something before continuing on, e.g. getting valid input from the user.
The beginning-exit loop is used when you want to avoid doing something if the situation is not appropriate, e.g., repeatedly writing something starting at a specific place on the screen -- the starting point may not be a valid screen location.