ReadAndSum
Program ReadAndSum;
{ This program extends the program SumThem by reading
the five values to sum from a file using another procedure
called ReadFive()
IMPORTANT: The file 'rs_data.txt' MUST EXIST on the a: drive.
See procedure ReadFive for file data format details.
}
{ set up a type that defines an array of 5 elements each of
type real. This way we don't have to repeatedly type
array[1..5] of real.
}
type
tp_Array5 = array[1..5] of real;
var
infile : text;
nums : tp_Array5;
the_sum : real;
{ ----------------------------------------------------------------
ReadFive
Read five numbers (of type real) into num_list[] from the
file assigned to in_file.
Note we assume each number is on a separate line.
---------------------------------------------------------------- }
procedure ReadFive(var in_file : text; var num_list : tp_Array5);
var
i : integer; { i is a local variable of ReadFive }
begin
i := 1;
while (i <= 5) do
begin
readln(in_file, num_list[i]);
i := i + 1;
end; { while }
end; { ReadFive }
{ ----------------------------------------------------------------
CalcSum
Calculate the sum of the numbers in num_list[]
---------------------------------------------------------------- }
procedure CalcSum(num_list : tp_Array5; var sum : real);
var
i : integer; { i is a local variable of CalcSum }
begin
sum := 0.0; { initialize sum to be zero }
i := 1;
while (i <= 5) do
begin
sum := sum + num_list[i];
i := i + 1;
end; { while }
end; { CalcSum }
{ ----------------------------------------------------------------
main program begins
---------------------------------------------------------------- }
begin
{ First we must open the file for reading }
assign(infile, 'a:rs_data.txt');
reset(infile);
ReadFive(infile, nums);
CalcSum(nums, the_sum);
writeln('The sum of the numbers is: ', the_sum:0:3);
{ always be sure to close the file }
close(infile);
end. { main program }
Here is a file
to test the above program on.