Next: Example Program: Student mark Up: The while statement Previous: Example while loop: Table

Example while loop: Average, Minimum and Maximum Calculation

In section 15.2 an algorithm was designed given the following requirement specification:

A user is to enter positive float values from the keyboard when prompted by the program. To signal end of input the user enters a negative integer. When data entry has terminated the program should output the minimum value entered, the maximum value entered and the average of the positive values entered. If there is no data entry (the user enters a negative number initially) then the program should output a message indicating that no data has been entered.

The final version of the algorithm was:

set sum to zero.
set count to zero.
enter first value.
set minimum and maximum to this value.
while (value is positive)
    {
     add value to sum.
     add one to count.
     if value is bigger than maximum then
                     set maximum to value.
     if value is smaller than minimum then
                      set minimum to value.
     read a value.
    }
if count is zero
    then output `no data entry'
    else {
          set average to sum/count.
          output count, average, maximum and minimum.
         }

The above algorithm can be written in C++ as follows:

// IEA Aug 96
// Reads in positive data until a negative number
// is entered and calculates the average and the
// maximum and minimum of the positive entries.

#include <iostream.h>

void main()
{
  float value, sum;
  float average, minimum, maximum;
  int count;
     // initialise
  sum = 0.0;
  count = 0;
  cout << "Enter a value: ";
  cin >> value;
  minimum = value;
  maximum = value;
  while (value >= 0.0)
    {
         // process value
      sum += value;
      count++;
      if (value > maximum)
         maximum = value;
      else if (value < minimum)
        minimum = value;
         // get next value
      cout << "Enter a value: ";
      cin >> value;
    }
  if (count == 0)
    cout << "No data entry" << endl;
  else
    {
      average = sum / count;
      cout << "There were " << count << " numbers" << endl;
      cout << "Average was " << average << endl;
      cout << "Minimum was " << minimum << endl;
      cout << "Maximum was " << maximum << endl;
    }
}
Download program.



Next: Example Program: Student mark Up: The while statement Previous: Example while loop: Table