![](../header/home2.jpg) |
Chapter 1
Introduction to DOS
Chapter 2
Introduction to Turbo Pascal
Chapter 3
Parts of a Pascal Program
Chapter 4
Control Structures and Looping
Chapter 5
Looping
Chapter 6
Procedures
Chapter 7
Parameters Passing
Chapter 8
Functions
Chapter 9
Arrays
Chapter 10
Searching and Sorting
Chapter 11
Records and File of Records
|
CHAPTER 5
( Looping )
Any programming
problem could be solved by using combinations
of :
(1) simplesequence,
(2) decision structure,
(3) loop and
(4) subroutines (procedures and functions).
In this chapter we will study looping.
Turbo Pascal provides four loop structures, WHILE,
REPEAT, FOR, and WITH. We will not be discussing WITH in this
section; it will be discussed along with records.
WHILE DO
STATEMENT:
Suppose a teacher wishes
to calculate average grades for an entire class of 20
students. The same calculations need to be repeated 20 times.
If simple sequence is used, the instructions will have to be
repeated 20 times.
A while do loop can be used to accomplish this:
|
PROGRAM 5-1
Program LoopEx1 (input,output);
var
count, score1, score2, score3,
score4 : integer;
average : real;
begin
Count :=1;
while count <= 20 do
begin
Writeln ('Please enter four
scores separated by space');
readln (Score1, score2, score3, score4);
Average := (Score1 + score2 + score3 + score4) / 4;
writeln ('Average: ', Average:6:2);
Count := Count+1;
end;
end.
|
Program run
C:\TP>
Turbo Pascal Version 6.0 Copyright (c) 1983,90
Borland International
Please enter four scores separated by space
80 90 60 75
Average: 76.25
Please enter four scores separated by space
44 49 90 99
Average: 70.50
Please enter four scores
separated by space
... program continues for
total of 20 different students.
This program will find the average of four scores
for twenty students. To keep a count of how many we have done so far
we use a counter called count. Count is incremented each time after
the average of a set of scores has been calculated. We will begin
with a one, after we calculate the first student's average the count
will be incremented to two. Incrementing is done as follows:
Count := Count + 1;
This statement requires a special understanding. As
we learned earlier, a variable is a name of a memory location. So
there is a memory location called Count. With this instruction we
are telling Pascal to add 1 to the number currently in the location
called count, and to place the resulting number in the same memory
location. Therefore, if count currently has 1, after carrying out
this instruction, count will have a value of 2.
Now that we know how to keep track of how many
averages we have done, we need some way of telling Pascal to do the
same set of instructions (to find the average) over and over again
until we have calculated averages for all twenty students. This is
accomplished by:
while count <= 20 do
begin
.
.
end;
Every instruction within the begin-end pair will be
repeated as long as count is less than or equal to 20. If count is
greater than 20 then the loop will terminate. In order for this loop
to work properly, it is quite apparent that the count should have a
value twenty or below for the loop to work. So we initialize the
counter to 1. After the calculation is done, we increment the count
by 1.
count := 1;
while count <= 20 do
begin
.
.
count := count + 1
end;
Here is some more information about the while loop.
The expression controlling the repetition (loop control variable -
LCV) is evaluated BEFORE the loop is executed. Therefore, the
controlling expression MUST be initialized first. In this example,
Count is initialized to 1. At the BOTTOM OF THE LOOP the controlling
expression must be changed. If not, an endless loop will occur.
Suppose we forgot to increment the counter and the value of count
remains as 1. Since the value of count is 1, the loop will continue
to execute without ever going to the next statement after the loop.
If this happens, you may even have to turn the computer off. So
don't forget, initialize the LCV above the loop and change the value
of LCV inside the loop.
If we had initialized the LCV
to 21 (instead of 1), the loop would not be executed at all. This is
because when Pascal checks the condition, count <= 20, it will
receive the value false.
REPEAT UNTIL STATEMENT:
Let us modify the above program PROGRAM 5-1 to use
a different loop structure. If you look very closely you can see the
fine difference between the while structure and the repeat
structure. The while structure looks at the LCV first to make sure
the condition is satisfied; the repeat until structure does the loop
and then checks to see if it should exit. As you can see, the repeat
structure will go through the loop at least once, whereas the while
loop may not go through the loop at all.
PROGRAM 5-2
Program LoopEx2 (input,output);
var
count, score1, score2, score3,
score4 : integer;
average : real;
begin
Count :=0;
Repeat
Count := Count+1;
Writeln ('Please enter four scores separated by
space');
readln (Score1, score2, score3, score4);
Average := (Score1 + score2 + score3 + score4) / 4;
writeln ('Average: ', Average:6:2);
until Count = 20;
end.
|
Program run:
C:\TP>exit
Please enter four scores separated by space
85 90 44 33
Average: 63.00
Please enter four scores separated by space
66 33 90 56
Average: 61.25
Please enter four scores separated by space
Program run continues for 20 students...
The statements between the symbols REPEAT and UNTIL
are executed in sequence until the expression yields true. The
condition is evaluated at the BOTTOM of the loop. Therefore, the
loop is executed at least once. Notice in this example Count is
initialized to 0 above the loop. As soon as the loop is entered the
count is incremented to 1. Then at the bottom of the loop it is
evaluated:
Count :=0;
repeat
Count := Count +1;
.
.
until count = 20;
Among the other differences between the while loop
and the repeat loop, the LCV will end up with different values (this
is not always true, however). After termination of the while loop,
the LCV would have the value of 21. After the repeat loop the LCV
would have a value of 20.
FOR DO STATEMENT
If you know exactly how many time a sloop must be
executed, then Pascal provides you with another version of the WHILE
loop called the FOR DO loop. It works identically to the while loop,
except Pascal takes care of initializing, incrementing, and checking
the LCV.
So why not use the FOR DO loop always? For Do loop
is limited to doing a loop a particular number of times. Whereas the
While loop and Repeat loops can be used with any kind of condition.
You may want to say 'while not(end of file) do' or 'repeat..until
end of file'. Here you do not know exactly how many times to do it,
but to do it until the end of file has been reached.
PROGRAM 5-3
Program LoopEx3 (input,output);
var
count, score1, score2, score3,
score4 : integer;
average : real;
begin
For Count := 1 to 20 do
begin
Writeln ('Please enter four
scores separated by space');
readln (Score1, score2, score3, score4);
Average := (Score1 + score2 + score3 + score4) / 4;
writeln ('Average: ',
Average:6:2);
end;
end. |
Program run:
Please enter four scores separated by
space
89 89 90 78
Average: 86.50
Please enter four scores separated by space
99 99 78 88
Average: 91.00
Please enter four scores
separated by space
Program run continues for 20 students...
Pascal assigns the first and
last value of the control variable based on the FOR
statement. The control variable
must be of an ordinal type and the value assigned should be
compatible with that type. Ordinal type means that a type that has
an order: something comes before it and something comes after it.
For example, take a 10; we know 9 comes before ten and 11 comes
after. Take the character 'C', we know 'B' comes before it and 'D'
comes after it. You can count down using downto (instead of to in
counting up).
If these three loop concepts are difficult to
follow, you need to study and compare the following few programs.
Review these programs several times. Suppose we want to display 1 to
100 on the screen we could write some thing like this:
Program CountUp (output);
var
begin
count := 1; {initialize count to 1}
writeln(count); {prints 1}
count := count +1; {increment count by 1}
writeln(count); {print 2}
count := count +1; {increment count by 1}
writeln(count); {print 3}
. {continue these steps}
. {for a total of 100
times}
end.
As you can see this can be a very tedious process.
You will get very bored with writing the same lines over and over
again. The following three programs do the same thing, writes 1 to
100 on the screen.
PROGRAM 5-4
Program Count1 (output);
{EXAMPLE USING WHILE LOOP}
var
begin
count := 1; {INITIALIZE LCV}
while count <= 100 do {TEST CONDITION}
begin
end
end.
|
Program run:
C:\TP>
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32
33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48
49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64
65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80
81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96
97 98 99 100
PROGRAM 5-5
Program Count2 (output);
{EXAMPLE USING REPEAT LOOP}
var
begin
count := 0; {INITIALIZE LCV}
repeat
count := count +1; {CHANGE LCV}
write(count):5;
until count = 100; {TEST CONDITION}
writeln;
end.
|
Program run:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32
33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48
49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64
65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80
81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96
97 98 99 100
Type EXIT to return to Turbo Pascal...
PROGRAM 5-6
Program Count3 (output);
{EXAMPLE USING FOR DO LOOP}
var
{PASCAL INITIALIZES COUNT TO 1}
begin
end.
|
All these three programs are self explanatory. No
further explanation is given here. If you have any questions, please
re-read this chapter. I had mentioned that you could count down as
well. Here is a program that will count down from 100 to 1.
PROGRAM 5-7
Program CountDown (output);
var
begin
for count := 100 downto 1 do
write(count:5)
writeln;
/ul>end. |
Program run:
C:\TP>exit
100 99 98 97 96 95 94 93 92 91 90 89 88 87 86 85
84 83 82 81 80 79 78 77 76 75 74 73 72 71 70 69
68 67 66 65 64 63 62 61 60 59 58 57 56 55 54 53
52 51 50 49 48 47 46 45 44 43 42 41 40 39 38 37
36 35 34 33 32 31 30 29 28 27 26 25 24 23 22 21
20 19 18 17 16 15 14 13 12 11 10 9 8 7 6 5
4 3 2 1
Type EXIT to return to Turbo Pascal...
Now let us write A..Z and then backwards (Z..A).
Here also we will use the for loop:
PROGRAM 5-8
Program DisplayABC (output);
var
begin
{write A..Z}
for character := 'A' to 'Z' do
write(character);
writeln; {go to the next line}
{now write it backwards}
for character := 'Z' downto 'A' do
write(Character);
writeln;
end.
|
Program run:
Type EXIT to return to Turbo Pascal...
ASSIGNMENTS FOR CHAPTER 5
1. Write a program to write every even number from
0 to 100 using the while loop.
2. Rewrite the above program using repeat until loop.
3. Write a program to read names until 'END' is entered for the name.
4. Modify the program below so that if the second
number entered is zero then it will print 'You must
enter a non-zero number, please try again'
and will ask for the inputagain.
PROGRAM 5-9
Program calculator (input,
output);
var
firstNumber, SecondNumber, Result : real;
operator : char;
begin
{write introduction and instructions}
writeln('This program will add, subtract, multiply, or
writeln('divide two numbers. It is ask for one number, ');
writeln(' then the operator (only enter +, -, *, or /)
');
writeln(' and finally for the second number.');
{ask for numbers and the operator}
writeln;
write('Enter a number ');readln(firstNumber);
write('Operator ');readln(operator);
write('Enter second number (must be non-zero) ');
readln(secondNumber);
{do the calculation based on the operator}
CASE operator of
'+' : result := firstnumber + secondNumber;
'-' : result := firstnumber - secondNumber;
'*' : result := firstnumber * secondNumber;
'/' : result := firstnumber / secondNumber;
else
begin
writeln ('I do not recognize that operator!');
result := 0;
end;
end; {end the case}
writeln ('The result is: ',result:9:2)
end. |
Program run:
This program will add, subtract, multiply, or
divide two numbers. It is ask for one number,
then the operator (only enter +, -, *, or /)
and finally for the second number.
Enter a number 15
Operator *
Enter second number (must be non-zero) 5
The result is: 75.00
Type EXIT to return to Turbo Pascal...
Microsoft(R) MS-DOS(R) Version 5.00
(C)Copyright Microsoft Corp 1981-1991.
C:\TP>
Go to top of this
chapter
| |