I need to remove the lowest test score and then the average should only average
ID: 3544531 • Letter: I
Question
I need to remove the lowest test score and then the average should only average the remaining scores.
#include<iostream>
using namespace std;
void sort_array(int array[],int size)
{
// using insertion sort to sort the array
for (int i = 1; i < size; i++)
{
int temp = *(array+i);
int j;
for (j = i; j > 0 && temp < *(array+j-1); j--)
{
*(array+j) = *(array+j-1);
}
*(array+j) = temp;
}
}
double calcualte_average(int array[],int size)
{
double sum = 0;
for(int i=0; i<size; i++)
sum = sum + *(array+i);
return (sum/size);
}
int main()
{
int no_of_scores;
int* array;
cout <<"How many total scores are there :";
cin >> no_of_scores;
cout << endl;
array = new int[no_of_scores];
for(int i=0; i<no_of_scores; i++)
{
cout << "Enter Score " << (i+1) << endl;
cin >> *(array+i);
cout << endl;
if(*(array+i) < 0)
{
cout<< "Invalid Test Score ";
i--;
}
}
sort_array(array,no_of_scores);
cout <<"After sorting test scores are :" << endl;
for(int i=0; i<no_of_scores; i++)
cout << array[i] << " ";
cout << endl;
cout <<"Average of Scores given by " << calcualte_average(array,no_of_scores) << endl;
return 0;
}
Explanation / Answer
#include<iostream>
using namespace std;
void sort_array(int array[],int size)
{
// using insertion sort to sort the array
for (int i = 1; i < size; i++)
{
int temp = *(array+i);
int j;
for (j = i; j > 0 && temp < *(array+j-1); j--)
{
*(array+j) = *(array+j-1);
}
*(array+j) = temp;
}
}
double calcualte_average(int array[],int size)
{
double sum = 0;
for(int i=0; i<size; i++)
sum = sum + *(array+i);
return (sum/size);
}
int main()
{
int no_of_scores;
int* array;
cout <<"How many total scores are there :";
cin >> no_of_scores;
cout << endl;
array = new int[no_of_scores];
for(int i=0; i<no_of_scores; i++)
{
cout << "Enter Score " << (i+1) << endl;
cin >> *(array+i);
cout << endl;
if(*(array+i) < 0)
{
cout<< "Invalid Test Score ";
i--;
}
}
sort_array(array,no_of_scores);
cout <<"After sorting test scores are :" << endl;
for(int i=0; i<no_of_scores; i++)
cout << array[i] << " ";
cout << endl;
cout <<"After removing the lowest scores ,the scores are :" << endl;
for(int i=1; i<no_of_scores; i++)
cout << array[i] << " ";
cout << endl;
cout <<"Average of Scores after removing the lowest score is given by : " << calcualte_average((array+1),no_of_scores-1) << endl;
return 0;
}