In: Computer Science
Task 1
Write a program that allocates an array large enough to hold 5 student test scores. Once all the scores are entered, the array should be passed to a function that sorts them in ascending order. Another function should be called that calculates the average score. The program should display the sorted list of scores and averages with appropriate headings.
Input Validation: Do not accept negative numbers for test scores.
Task 2
Modify the program so the lowest test score is dropped. This score should not be included in the calculation of the average.
Task 3
Modify the program to allow the user to enter name-score pairs. For each student taking a test, the user types the student’s name followed by the student’s integer test score. Modify the sorting function so it takes an array holding the student names and an array holding the student test scores. When the sorted list of scores is displayed, each student’s name should be displayed along with his or her score.
C++
#include <bits/stdc++.h>
using namespace std;
void sort_task1(int arr[5])
{
int n = 5;
sort(arr, arr+n);
cout<<"Sorted list of Marks: ";
for(int i=0;i<n;i++)
{
cout<<arr[i]<<"\t";
}
}
void avg_task1(int arr[5])
{
int sum=0;
int n = 5;
for(int i=0;i<n;i++)
{
sum+=arr[i];
}
int avg;
avg=sum/n;
cout<<"Avg :"<<avg<<endl;
}
void sort_task2(int arr[])
{
int n = 5;
sort(arr, arr+n);
for(int i=0;i<n-1;i++)
{
arr[i]=arr[i+1];
}
arr[5]=0;
cout<<"Sorted list of Marks: ";
for(int i=0;i<n-1;i++)
{
cout<<arr[i]<<"\t";
}
}
void avg_task2(int arr[])
{
int sum=0;
int n = 4;
for(int i=0;i<n;i++)
{
sum+=arr[i];
}
int avg;
avg=sum/n;
cout<<"Avg :"<<avg<<endl;
}
void sort_task3(vector<pair<int,string>> vp)
{
int n = 5;
sort(vp.begin(), vp.end());
cout<<"Sorted list of Marks: "<<endl;
for(int i=0;i<n;i++)
{
cout<<vp[i].second<<" "<<vp[i].first<<endl;
}
}
void avg_task3(vector<pair<int,string>> vp)
{
int sum=0;
int n = 5;
for(int i=0;i<n;i++)
{
sum+=vp[i].first;
}
int avg;
avg=sum/n;
cout<<"Avg :"<<avg<<endl;
}
int main()
{
int arr[5];
int x;
for(int i=0;i<5;i++)
{
cin>>x;
while(x<0)
{
cout<<"Invalid number,Enter again"<<endl;
cin>>x;
}
arr[i]=x;
}
//Task 1
sort_task1(arr);
avg_task1(arr);
//Task 2
sort_task2(arr);
avg_task2(arr);
//Task 3
vector<pair<int,string>> v;
for(int i=0;i<5;i++)
{
string name;
int marks;
cin>>name>>marks;
while(marks<0)
{
cout<<"Invalid number,Enter again"<<endl;
cin>>name>>marks;
}
v.push_back({marks,name});
}
sort_task3(v);
avg_task3(v);
return 0;
}
Note: I have taken avg in all avg functions as int.
You can type cast them as float if you want.