ReadAndSum2



Program ReadAndSum2;

{ This program extends the program ReadAndSum by not only
  reading the five values to sum from a file, but
  also a Name (which comes before the number list in
  the file).

  IMPORTANT: The file 'rs_data2.txt' MUST EXIST on the a: drive.
  See procedure ReadFive for file data format details.
}

type
   tp_Array5 = array[1..5] of real;  { array of 5 numbers }
   tp_String40 = string[40];         { our name string TYPE }

var
   infile  : text;
   name    : tp_String40;
   nums    : tp_Array5;
   the_sum : real;


{ ----------------------------------------------------------------
  ReadFive
  Read first a NAME into name and then five numbers (of type real)
  into num_list[] from the file assigned to in_file.
  Note we assume the name is the first thing in the file, the name
  is on its own line and each number is on a separate line.
  ---------------------------------------------------------------- }

procedure ReadFive(var in_file : text;
                   var num_list : tp_Array5; var name : tp_String40);
var
   i : integer;    { i is a local variable of ReadFive }

begin

   { first we read the name }
   readln(in_file, name);

   { then we go after the numbers }
   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_data2.txt');
   reset(infile);

   ReadFive(infile, nums, name);

   CalcSum(nums, the_sum);

   writeln('The name is: ', name);
   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.