Back to DFS's Pascal Page


Two Loops & Flow Charting

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.

The Repeat-Until Loop

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:

  1. the reserved word REPEAT to indicate the beginning;
  2. a statement to print the value of num;
  3. an assignment statement to increment the value of num by one;
  4. the reserved word UNTIL with a condition to indicate the end.

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.

The While-Do Loop

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:

  1. the reserved words WHILE and DO with a condition indicate that a set of statements is about to be specified;
  2. BEGIN to indicate the beginning;
  3. a statement to print the value of num;
  4. an assignment statement to increment the value of num by one;
  5. the reserved word END to indicate the end.

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.


© 1997-2004 DFStermole
HTMLified: 28 Dec 99 Last updated: 15 Feb 04