Please help me complete this code so that it sorts the class list in respect to
ID: 3659216 • Letter: P
Question
Please help me complete this code so that it sorts the class list in respect to the grades
#include <iostream>
#include <string>
using namespace std;
struct Student{
string firstname, lastname;
int ID;
float score;
};
void sort(Student myArray[],int size){//function sorts the elements of the array
for(int i = size-1; i>0; i--)//checks size
for(int j = 0; j<i; j++)//checks the array
{
if(myArray[j]> myArray[j+1])
{//swapping the array elements
int temp = myArray[j+1];//temp stores the sorted value
myArray[j+1] = myArray[j];
myArray[j] = temp;
}
}
}
int main()
{
int counter = 1;
cout<<"Enter the size of the array: ";
int sz; cin>>sz;
Student *sPtr = new Student[sz];
cout<<"Let's populate the array ";
for(int i=0; i<sz; i++)
{
cout<<"Enter the firt name followed by last name: ";
cin>>sPtr[i].firstname;
cin>>sPtr[i].lastname;
cout<<"Enter ID for "<<sPtr[i].firstname<<": ";
cin>>sPtr[i].ID;
cout<<"Enter score for "<<sPtr[i].firstname<<": ";
cin>>sPtr[i].score;
cout<<endl;
}
cout<<"Let's print the class list ";
cout<< " Sl FirstName LastName ID Grade";
for(int i=0; i< sz; i++) {
cout<< " "<<counter++<<" "<< sPtr[i].firstname<< " "<< sPtr[i].lastname<< " "<<sPtr[i].ID<< " "<< sPtr[i].score<<endl;
}
}
Explanation / Answer
everthing is correct but there is a mistake in your sort function so i am correcting that: corrected code : void sort(Student myArray[],int size) { //function sorts the elements of the array for(int i = size-1; i>0; i--)//checks size for(int j = 0; j { if(myArray[j].score> myArray[j+1].score) {//swapping the array elements int temp = myArray[j+1].score;//temp stores the sorted value myArray[j+1].score = myArray[j].score; myArray[j].score = temp; } } } now rate me :)
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.