home *** CD-ROM | disk | FTP | other *** search
/ PC Media 7 / PC MEDIA CD07.iso / share / prog / cm / average.cpp next >
Encoding:
C/C++ Source or Header  |  1994-08-31  |  2.1 KB  |  51 lines

  1. // average.cpp
  2. //
  3. // Example program uses the array class and the example class defined in
  4. // the file "integer.h".  The program reads in a set of test scores with
  5. // values between 0 and 100, stuffs each one into an array, and then gets
  6. // the average score which is then printed to standard output.  This
  7. // example could be greatly improved by defining mathematical operators
  8. // for the integer class.
  9. //
  10. #include <cm/include/cmarray.h>
  11. #include "integer.h"
  12.  
  13. const Integer MIN(0);                            // Define minimum and
  14. const Integer MAX(100);                          // maximum score constants.
  15.  
  16. int main()                                       // Start main.
  17. {
  18.   CmArray array;                                 // Declare array.
  19.   Integer howMany;                               // Number of scores.
  20.   Integer input;                                 // Input score.
  21.  
  22.   cout << "How many scores will you enter: " << flush;
  23.   cin  >> howMany;                               // Read in number of scores.
  24.   array.resize((int) howMany);                   // Set array size.
  25.  
  26.   int ii = 0;                                    // Loop counter.
  27.   while (ii < (int) howMany)                     // While still in range,
  28.   {
  29.     cout << "Score " << ++ii << ": " << flush;
  30.     cin  >> input;                               // read score.
  31.     if (input < MIN || input > MAX)              // Check score range.
  32.     {
  33.       cout << "Score must be between " << MIN << // Bad range.
  34.               "and " << MAX << endl; ii--;
  35.     }
  36.     else
  37.       array.add(new Integer(input));             // Add score to array.
  38.   }
  39.  
  40.   CmArrayIterator iterator(array);               // Create an iterator.
  41.   int             average  = 0;                  // Start total at zero.
  42.   while (iterator)                               // While still iterating,
  43.   {
  44.     Integer *pInt = (Integer*) iterator++;       // Cast to Integer type.
  45.     average += (int)(*pInt);                     // Add to total.
  46.   }
  47.                                                  // Print average.
  48.   cout << "\nAverage score is " << average / (int) howMany << ".\n";
  49.   return 0;
  50. }
  51.