|
~ Introduction to Programming: Pascal ~ Session 10 - Arrays and Intro to Databases |
So
far, we have looked at variables that store a single piece of information –
e.g. a string variable to store a single name might be defined as:-
var
name:String;
Sometimes
it is useful to be able to store a whole series of variables. For example, if we
wanted to add three numbers together and find the average, up to now, we might
have created a program like this:-
program
prog11_1;
uses
Crt;
var
num1,num2,num3,average:real;
begin
clrScr;
write('Enter
first number: ');
readLn(num1);
write('Enter
second number: ');
readLn(num2);
write('Enter
third number: ');
readLn(num3);
average
:= (num1+num2+num3)/3.0;
writeLn('Average
of three numbers is ',average:5:2);
readKey;
end.
Try
typing this in and running it. Now let's say we wanted to add up five numbers.
Or fifty. We get a very long program. Or, we can add the number up in a total as
we go along, and use a loop.
We
can also opt to make use of an array variable. This is a variable that
can store more than one value in it. For example, if we wanted a list of numbers
to average, we could define an array as follows:-
var
num : array [1..3] of real;
This
means that we are creating a variable called num which holds three
numbers (labelled one to three – the .. symbols can be read as to),
each of which is of type real.
Thus,
the array variable now looks something like this:-

So,
to set the first item in the array to be 1.5, we would use:-
Num[1] := 1.5;
Similarly,
to access the value again, we might use:-
WriteLn('First element of array is ',Num[1]:3:1);
To
set the second element of the array to 0.5 and the third to 1.0:-
Num[2] := 0.5;
Num[3] := 1.0;
Thus,
the Num array would now look something like this:-

And
to find the average of the three:-
Average:=(Num[1]+Num[2]+Num[3])/3.0;
This
would produce a result of (1.5+0.5+1.0)/3.0 = 1.0
So
what's the advantage of using an array over declaring them individually? Let's
say we wanted to find an average of 10 numbers. Type in the following program
and run it:-
program
prog11_2;
uses
Crt;
const
valuesToAverage = 10;
var
num : array [1..valuesToAverage] of real;
total,average:real;
i
: integer;
begin
clrScr;
for
i := 1 to valuesToAverage do
begin
write('Enter
number ',i,': ');
readLn(num[i]);
end;
total:=0.0;
writeLn;
write('Average of: ');
for i
:= 1 to valuesToAverage do
begin
write(num[i]:3:2);
if
(i<valuesToAverage) then write(',');
total
:= total + num[i];
end;
average
:= total / valuesToAverage;
writeln('
is ',average:6:2);
readKey;
end.
Try
running this with the following values. Type each value on a separate line.
2,4,6,8,10,12,14,16,18,20
These
numbers add up to 110. As there are 10 of them, the average is 11.0
The
output of your program should look something like this (see overleaf) :-
Enter
number 1: 2
Enter
number 2: 4
Enter
number 3: 6
Enter
number 4: 8
Enter
number 5: 10
Enter
number 6: 12
Enter
number 7: 14
Enter
number 8: 16
Enter
number 9: 18
Enter
number 10: 20
Average
of: 2.00,4.00,6.00,8.00,10.00,12.00,14.00,16.00,18.00,20.00 is
11.00
Try
the program again, but change the value of the constant valuesToAverage
from 10 to 5.
You
can see that by changing this single value, the program can store any number of
values without making the program any longer.
Exercise
1.
Add a line to display the total on the screen.
2.
Work out the minimum and maximum values typed. Hint: Create two variables
for each of minimum and maximum. In either of the for
loops, put in a test (use if) to see whether the value of minimum
is greater than the array element's value. If it is, then set the value of
minimum to the array element's value – if mimimum > num[i]
then minimum := num[i];
You will need a similar line for the maximum variable, but the
condition (<) will be different.
You will then need a line to display the values of minimum and maximum
on the screen (after the end of the for loop).
Note that you will also need initial values for minimum and maximum (before the
start of the loop!) – I would suggest something small (e.g. 0) for the maximum
and something large (e.g. 99999999) for the minimum.
A Simple Database
A database is a program that allows
you to add, change, and read information from a storage location – typically a
file. It is one of the most widely used applications in business programming, so
it's well-worth understanding the principles of writing such an application.
First of all, create an
empty database file in the c:\temp directory called NAMES.TXT. A
simple way of doing this is to open Windows Explorer (usually available from
Start | Programs | Accessories | Windows Explorer) and navigate to the C: drive
(you may have to open up My Computer first). Open the temp
directory (if you have one), otherwise create a new temp directory.
Double-click on the temp directory and in a blank space in the list of
files on the right-hand side, click on the right-hand mouse button, select the New
option, and select the Text Document option. Enter over where it says New
Text Document with the file name names
- this
will create a new blank text file. If there was an extension .txt at the
end of the filename, keep this intact, otherwise don't include
the extension – Windows is hiding it for you!
Now type in the following program,
which is a very simple database program:-
program
dbase1;
uses
Crt;
const
fileName = 'C:\TEMP\NAMES.TXT';
maxRecords = 100;
var
name : array [1..maxRecords] of String;
address : array [1..maxRecords] of String;
numRecs : integer;
i,thisRec : integer;
inFile, outFile : TEXT;
ch : char;
begin
assign(inFile, fileName); reset(inFile);
numRecs:=0;
while not eof (inFile) do
begin
inc(numRecs);
readLn(inFile,name[numRecs]);
readLn(inFile,address[numRecs]);
end;
close(inFile);
repeat
writeLn; writeLn; writeLn;
writeLn('Database Program');
writeLn('----------------');
for i:=1 to numRecs do
writeLn(i,': ',name[i]);
writeLn;
repeat
write('Options: [a]dd, [u]pdate, [d]elete, [r]ead, [e]xit: ');
ReadLn(ch); ch:=UpCase(ch);
until (ch='A') or (ch='U') or (ch='D') or (ch='R')
or (ch='E');
writeLn;
if (ch='A') then
begin
if numRecs = maxRecords then
writeLn('Maximum number of records has been reached')
else
begin
numRecs:=numRecs+1;
write('Enter new name:
');
readLn(name[numRecs]);
write('Enter new address: ');
readLn(address[numRecs]);
end;
end;
if (ch='U') then
begin
write('Which record number do you wish to update? ');
readLn(thisRec);
if (thisRec<1) or (thisRec>numRecs) then
writeLn('Record number must be between 1 and ',numRecs)
else
begin
write('Enter name:
');
readLn(name[thisRec]);
write('Enter address: ');
readLn(address[thisRec]);
end;
end;
if (ch='D') then
begin
write('Which record number do you wish to delete? ');
readLn(thisRec);
if (thisRec<1) or (thisRec>numRecs) then
writeLn('Record number must be between 1 and ',numRecs)
else
begin
for i:=thisRec to numRecs - 1 do
begin
name[i] := name[i+1];
address[i] := address[i+1];
end;
numRecs:=numRecs-1;
end;
end;
if (ch='R') then
begin
write('Which record number do you wish to read? ');
readLn(thisRec);
if (thisRec<1) or (thisRec>numRecs) then
writeLn('Record number must be between 1 and ',numRecs)
else
begin
writeLn;
writeLn('Record no.',thisRec);
writeLn('-------------');
writeLn(' Name: ',name[thisRec]);
writeLn('Address: ',address[thisRec]);
end;
end;
until ch='E';
assign(outFile, fileName); rewrite(outFile);
for i:=1 to numRecs do
begin
writeLn(outFile,name[i]);
writeLn(outFile,address[i]);
end;
close(outFile);
end.
Compared
to the previous examples, this seems quite mammoth. However, it demonstrates all
of the major principles of storing and retrieving information from a database.
Test
the program as follows:-
1.
Enter A to add a new record.
2.
Enter a name – e.g. Fred Bloggs
3.
Enter an address – e.g. 23 Bloggs Road, Blogsville
4.
Notice that the name is now shown, prefixed with a 1.
5.
Enter a R to read the record back again.
6.
Enter a 1 to retrieve record number 1.
7.
The name and address should be shown on the screen.
8.
Enter A to add another record.
9.
Enter another name – e.g. Arry Aardvark
10.
Enter an address – e.g. 12 Anteater avenue, Anthill
11.
Notice that two names are now shown, labelled 1 and 2.
12.
Enter a R to read the record back again.
13.
Enter a 3 to see what happens – there isn't a record
number 3!
14.
Enter a R to read the record back again.
15.
Enter a 0 to see what happens – there isn't a record
number 0!
16.
Enter a R to read the record back again.
17.
Enter a 2 to read the second record.
18.
Enter an E to write the details out to the file and
exit.
19.
Using notepad, have a look at the NAMES.TXT text file
to see what has been stored.
20.
Run the program again – the details are back again, having
been read from the text file.
21.
Enter A to add another record.
22.
Enter another name – e.g. Harry Potter
23.
Enter another address – e.g. 9 Potters Close, Pottonia
24.
Notice that three names are now shown, labelled 1, 2, and 3.
25.
Enter a R to read the record back again.
26.
Enter a 3 to read the third record.
27.
Enter U to update one of the records.
28.
Enter a 2 to update Arry Aardvark.
29.
Enter a new name – e.g. Larry Llama
30.
Enter a new address – e.g. 12 Dromedary Close, Egypt
31.
Notice that the name in the list has now been updated.
32.
Enter a R to read the record back again.
33.
Enter a 2 to see the address for Larry Llama.
34.
Enter D to delete a record.
35.
Enter 2 to delete Larry Llama
36.
Notice that there are now only 2 records – Larry Llama has
disappeared.
37.
Enter
E to exit – the data has been saved again!