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.
A basic sort of loop is known as the Repeat-Until structure. This loop has the feature that the exit-condition check is built into the end of the loop.
{ Print the first five Natural numbers }
num := 1;
REPEAT
writeln(num);
num := num + 1
UNTIL num > 5
Before the loop is begun, the counter called num is initialized to the first value desired. The loop itself consists of four statements:
After 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 is known as the While-Do structure. This loop has the advantage that the exit-checking condition is built into the start of the loop.
{ Print the first five Natural numbers }
num := 1;
WHILE num <= 5 DO
BEGIN
writeln(num);
num := num + 1
END
Before the loop is begun, the counter called num is initialized to the first value desired. The loop itself consists of five statements:
Before each iteration of the statements inside the loop, the condition is checked. Only if the condition is TRUE are the statements executed. N.B. This means that the statements inside the loop will NOT be executed even once if the condition is FALSE when the initial check is made.