Over and over ...
A loop is part of a program that gets repeated a
number of times. The very first Pascal program you did
had a loop in it. Loops can be conditional in which case
they repeat until something happens - a condition is
met - or they can be unconditional, in which case
they are repeated for a fixed number of times. You've
already seen an example of an unconditional loop -
look back at the first program in this tutorial. The loop
starts with...
FOR
index := 1 TO 10 DO
... and the instruction(s) to be repeated go between a
BEGIN
and an END
statement:
BEGIN
WRITELN(index)
END
In this case the variable called index is a
counter which controls the loop - it starts at 1 and goes
up to 10
i) Unconditional Loops
Recall Example 6 where a teacher wanted to read in
three marks and calculate the average. Now consider what
would happen if there were 10 or 20 or 200 marks...
...well this is what loops are designed for and if we
know in advance how many times the loop is to be
repeated, then so much the better!
Here's a different design for the program. As each
mark is read in, we're going to keep a running total:
1. get information
from user
2. calculate average
3. print results
Step 1 becomes:
1.1 set total to zero
1.2 loop for each student
1.3 prompt user to enter
mark
1.4 read in the mark
1.5 update the total
1.6 end loop
Step 2 is:
2.1 average = total /
number of marks
Step 3 is:
3.1 print out the
total marks
3.2 print out the average mark
So the complete design looks like this:
|