In: Computer Science
C++ Programming Chapter 7 Assignment:
Assignment #4 – Student Ranking :
In this assignment you are going to write a program that ask user number of students in a class and their names. Number of students are limited to 100 maximum. Then, it will ask for 3 test scores of each student. The program will calculate the average of test scores for each student and display with their names. Then, it will sort the averages in descending order and display the sorted list with students’ names and ranking.
Follow the Steps Below
All the explanations is given in the comments of the code itself.
Code--
#include<bits/stdc++.h>
using namespace std;
int main()
{
int i,j,size,t;
//prompt the user to enter the number of
students
cout<<"Enter the number of students: ";
cin>>size;
string name[size],temp;
int scores[size][3];
double average[size];
//prompt the user to enter the name of students
cout<<"Enter name of
students:"<<endl;
getline(cin,temp);
for(i=0;i<size;i++)
{
getline(cin,name[i]);
}
//prompt the user to enter three test scores
cout<<"Enter 3 test scores for students
mentioned:\n";
for(i=0;i<size;i++)
{
cout<<setw(30)<<name[i]<<": ";
cin>>scores[i][0]>>scores[i][1]>>scores[i][2];
}
//calculate average and display it
cout<<endl<<setw(30)<<left<<"Name"<<"Average"<<endl;
for(i=0;i<size;i++)
{
//calculate average
average[i]=double(scores[i][0]+scores[i][1]+scores[i][2])/3.0;
cout<<setw(30)<<left<<name[i];
cout<<setprecision(2)<<fixed<<average[i];
cout<<endl;
}
//sort the averages and names
for(i=0;i<size-1;i++)
{
for(j=0;j<size-i-1;j++)
{
if(average[j]<average[j+1])
{
//swap averages
t=average[j];
average[j]=average[j+1];
average[j+1]=t;
//swap names
temp=name[j];
name[j]=name[j+1];
name[j+1]=temp;
}
}
}
//displat after sorting
cout<<endl<<left<<setw(30)<<"Name"<<"Average"<<endl;
for(i=0;i<size;i++)
{
cout<<left<<setw(30)<<name[i];
cout<<setprecision(2)<<fixed<<average[i];
cout<<endl;
}
}
Code Screenshot--
Output Screenshot--
Note--
Please upvote if you like the effort.