Repeat Loops

A repeat loop carries on repeating until some condition is satisfied, so must run at least once.

In the following example the user is repeatedly asked for input until an integer within the required range is typed in. This is an example of validation. (It is not a very good example because it cannot cope with the input of a character other than a digit. Strict validation requires the input of a string, and this is covered in the Validation tutorial).

program RepeatLoop;
{$APPTYPE CONSOLE}
uses
  SysUtils;
var
  Num: integer;
begin
  repeat
    write('Enter an integer between 2 and 12 ');
    readln(Num);
  until (Num > 1) and (Num < 13);
  writeln(Num, ' is acceptable.');
  readln;
end.
Features introduced:
  • repeat loop

  • Validation

  • Use of and, with brackets round expressions

In programs so far it has been necessary to restart the program to try it with a different input. By repeating the code until false, the program will continue running:

program Integers2;
{$APPTYPE CONSOLE}
var
  Num1, Num2, Sum, Difference, Product : integer;
begin
  repeat 
    write('Please enter a whole number between 1 and 100 ');
    readln(Num1);
    write('Please enter another whole number between 1 and 100 ');
    readln(Num2);
    Sum := Num1 + Num2;
    Difference := Num1 - Num2;
    Product := Num1 * Num2;
    writeln(Num1 ,' + ', Num2,' = ', Sum);
    writeln(Num1 ,' - ', Num2,' = ', Difference);
    writeln(Num1 ,' * ', Num2,' = ', Product);
  until false;
end.
Programming - a skill for life!

Iteration: for loops, repeat loops and while loops