Activity 10-3 - Arrays as Class Members

You can use arrays with classes and structures in almost an identical way.  Here is an example:

class Data
     void set_distance(int d);
     void set_times(int i, double t);
     void display();
     void statistics( );
     double time[5];  //array of time in second
     int distance; //distance in meter
     double min, max, average;

The member functions are defined as:

void Data::set_distance(int d)
        distance = d;

void Data::set_times(int i, double t)
        time[i] = t;

void Data::display()
   cout << "Here is your best 5 times for \n";
   cout << distance << " meter \n";

   for(int i = 0;  i < 5; i++)
        cout << time[i] << endl;

Exercise 10.3
Write a program that uses class Data.  Your program first asks a runner for a distance and 5 of his/her best times in that event, and it will store the times in the array time.  Then it finds the best, the worst, and the average time for that runner.  Finally, it displays all five times, following by the worst, the best, and the average.

You need to write the function statistics.  Please note that we assume we are only dealing with 5 times.  So the statistics function is a simple function.  This program finds the fastest time as the best time, the slowest time as the worst time, and computes the average of 5 times for each event.

Array of Objects
It is possible to create an array of objects.  For example in the program that used the class AltMoney to create the objects of type money for two different people, then added two amounts of money, we could use an array to define the two objects as:

AltMoney m[2];

In this case, the first object is m[0] and the second object is m[1].  Note that previously, we created the two money objects using:

AltMoney m1, m2;

This does not seem to be much different from the one we defined using an array.  But wait, what if you wanted to create 100 objects of type AltMoney?  Which method is more convenient to use, then?

Once you used an array to create objects, you can perform computation on each one of the objects using the array index.  So, if you want to use the previously defined add function to add the money from the two new objects, you do not need to change the function definition.  The only change is in the function call:

sum.add(m[0], m[1]);

Previously, this was written as: sum.add(m1, m2);