Blaise Pascal, Pensees
Repetition involves the organisation of a block of actions that is executed a number of times according to controls. The control test can be placed at the beginning (e.g.,
while {condition} do {loop}
) or the end of the loop (e.g., repeat {loop} until {conditon}
), or with the condition set the iteration a set number as the loop (e.g., for {loop sequence} do {code}
).Consider a simple loop which reads a series of n real numbers, and prints out the sum and average of those numbers.
program averages (input, output);
var i, n : integer;
sum, next, average : real;
begin
sum := 0;
writeln ('Enter the number of values you want summed and averaged');
read (n);
for i := 1 to n do
begin
writeln ('Enter number');
read(next);
sum := sum + next
end;
average := sum/n;
writeln ('The total value is ', sum);
writeln ('The average value is ', average)
end.
Another simple example of the
repeat ... until
sequence computes the factorial of a number of integers, usually presented as n!
program factorial (input, output);
var sum, number, finalnumber : integer;
begin
sum := 1;
number := 1;
writeln ('Enter the number you want to factorial');
read (finalnumber);
repeat
sum := sum * number;
number := number + 1
until number = finalnumber+1;
writeln ('The factorial of n! ', finalnumber, ' is ', sum)
end.
Note that in this particular case the finalnumber condition to exit the loop, is finalnumber+1, otherwise it will exit one number early. Another way to express this would be with a
while .. do
loop, as follows:
program factorial2 (input, output);
var sum, number, finalnumber : integer;
begin
sum := 1;
number := 1;
writeln ('Enter the number you want to factorial');
read (finalnumber);
while number < finalnumber do
begin
sum := sum * number;
number := number + 1
end;
writeln ('The factorial of n! ', finalnumber, ' is ', sum)
end.
Note that there are memory limits on what can be achieved.
lev@racoon:~/programming/pascal$ ./factorial2
Enter the number you want to factorial
20
The factorial of n! 20
is 0
(The actual answer is 2432902008176640000 - if the variables were assigned as type real, the program would work).
One of the very powerful features of loops is the capacity to create loops within loops. For example, if the sum and average loop recognised unit sales, a loop could be constructed where the number of iterations represented a number of salespeople, the number of values represented days of the week (or month, etc), and comparative averages could be calculated and compared.