Vectors are an excellent option for storing many instances of related data. In a
ID: 3725175 • Letter: V
Question
Vectors are an excellent option for storing many instances of related data. In addition loop statements like for loops are perfect for working with vectors.
A teacher has a small class of 10 students taking an exam. The professor would like to enter the scores from the exam and then calculate the mean, median, and range of scores to display them.
Your job is to write a program that collects the 10 scores using a for loop. Then write a second for loop that calculates the mean, median, and range of the scores.
Finally display the mean, median, and range.
Explanation / Answer
#include <iostream>
#include <vector>
#include <string>
#include <algorithm>
using namespace std;
void display_vector(vector <double> &student_scores) {
for(int i =0; i < student_scores.size(); i++){
cout << student_scores.at(i) <<endl;
}
}
double find_mean(vector <double> &student_scores){
double sum;
for(int i = 0; i < student_scores.size(); i++)
sum += student_scores.at(i);
return sum/student_scores.size();
}
double find_median(vector <double> student_scores){
sort(student_scores.begin(), student_scores.end()); // sort student_scores
double median;
if (student_scores.size() % 2 == 0) // even
median = (student_scores[student_scores.size() / 2 - 1] + student_scores[student_scores.size() / 2]) / 2;
else // odd
median = student_scores[student_scores.size() / 2];
return median;
}
double find_min(vector <double> &student_scores){
double min = student_scores.at(0);
for(int i = 0; i < student_scores.size(); i++)
if(min > student_scores.at(i))
min = student_scores.at(i);
return min;
}
double find_max(vector <double> &student_scores){
double max = student_scores.at(0);
for(int i = 0; i < student_scores.size(); i++)
if(max < student_scores.at(i))
max = student_scores.at(i);
return max;
}
int main()
{
vector <double> student_scores;
int score;
for (int i = 0; i < 10; i++){
cout << "enter the student: " << i +1 << "score" <<endl;
cin >> score;
student_scores.push_back(score);
}
double mean, median, average, min , max;
mean = find_mean(student_scores);
median = find_median(student_scores);
min = find_min(student_scores);
max = find_max(student_scores);
display_vector(student_scores);
cout << " The mean is " << mean <<endl;
cout << " The median is " << median <<endl;
cout << " The min is " << min <<endl;
cout << " The max is " << max <<endl;
cout << " The range of values is " << min << "to " << max <<endl;
return 0;
}
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.