Pascal: Calculating an Average

program ex15;

var i, num, sum, num_values : integer;
average: real;
begin
  i:=0;
//counter for values entered
  sum := 0; average := 0;
//initialise
  writeln('Find an average');
  writeln ('Enter the number of values');
  readln(num_values);
  repeat
    writeln ('Enter value for number', i+1);
    readln (num);
    sum := sum + num;
//running total (gatherer)
    inc (i);
//increment number of values entered
    until i = num_values;
  average := sum / (num_values);
  writeln ('Sum of integers is ', sum);
  writeln ('Average is ', average:8:2);
  readln;
end.

We use a repeat..until loop to collect numbers from the user, using i as a counter to indicate how many numbers the user has entered. The loop finishes when the number of values collected equals the number that the user said he wanted to enter.

We calculate the sum inside the loop because the values do not persist, each new one overwrites the previous one. This running total is called a 'gatherer' as it collects or gathers the values that are overwritten each time the loop is entered. The counter starts at 0 and is increased inside the loop using inc(). We calculate the average outside the loop using the counter we incremented inside. Note that the average is a real number.

Back to questions