10.
You can use arrays with classes and structures in almost an identical way. Here is an
example:
class Data
{
public:
void set_distance(int d);
void set_times(int i, double t);
void display();
void statistics( );
private:
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;
}
}
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.
Answer-
#include<iostream>
using namespace std;
class RunnerData
{
public:
void set_distance(int d);
void set_times(int i, double t);
void display();
void statistics( );
private:
double time[5]; //array of time in second
int distance; //distance in meter
double min, max, average;
};
//The member functions are defined as:
void RunnerData::set_distance(int d)
distance = d;
void RunnerData::set_times(int i, double t)
{
time[i] = t;
void RunnerData::display()
{
cout << "Here is your best 5 times for "<< distance << " meter "<<endl;
for(int i = 0; i < 5; i++)
cout << time[i] << endl;
//defintion for statistics function
void RunnerData::statistics()
double sum = 0, avg;
double best = time[0];
double worst = time[0];
for(int i = 0; i< 5; i++)
//find the worst time
if(time[i] > best)
worst = time[i];
//find the best time
else if(time[i] < worst)
{
best = time[i];
//calculate sum
sum = sum + time[i];
//calculate the average time
avg = sum/5;
//displa the output
cout<<"Best time is: "<<best<<endl;
cout<<"Worst time is: "<<worst<<endl;
cout<<"Average time is: "<<avg<<endl;
//driver code
int main()
//creating a class object
RunnerData D;
//calling the functions
D.set_distance(100);
D.set_times(0, 12.16);
D.set_times(1, 12.50);
D.set_times(2, 9.34);
D.set_times(3, 10.45);
D.set_times(4, 11.23);
D.display();
D.statistics();
return 0;