In: Computer Science
following:
It prints the student’s id and GPA. If the student’s GPA is greater than or equal to 3.8, it prints “an honor student”.
Ans: Since It is not specified in the question hence all the data members are declared as private and an extra utility function to get average of GPA per course has been created. Alternative to this is declare gpa array as public and calculating average in the main function.
Also, assignRandom function is created just to populate the values in each instance of the class and hence it is not an essential function.
Note: Read comments in the code to get it's description.
#include<bits/stdc++.h>
using namespace std;
// Course Class
class Course{
private:
int* number_of_students;
int* sId;
double* gpa;
public:
// Constructor dynamically assigns memory
Course(int student_count){
number_of_students = new int;
*number_of_students = student_count;
sId = (int*)malloc(sizeof(int)*student_count);
gpa = (double*)malloc(sizeof(double)*student_count);
for(int i = 0; i<student_count; i++){
sId[i] = 0;
gpa[i] = 0;
}
}
// Function to add students at the end in a particular course
void enroll(int Id, double gpa_score){
int i = 0;
while(i<*number_of_students && sId[i] != 0)
i++;
// If no more students can be added then return
if(i == *number_of_students)
return;
sId[i] = Id;
gpa[i] = gpa_score;
}
// Function prints the required info per course
void print_info(){
int n = *number_of_students;
for(int i = 0; i<n; i++){
cout<<sId[i]<<"\t"<<gpa[i]<<"\t";
if(gpa[i] >= 3.8)
cout<<"An honor student";
cout<<"\n";
}
}
// Returns the average value of GPA in a particular course
double getAverage(){
double sum = 0.0;
for(int i = 0; i<*number_of_students; i++)
sum += gpa[i];
return sum/(*number_of_students);
}
// Destructor function
~Course(){
delete (number_of_students);
delete [] sId;
delete [] gpa;
}
};
// Utility function to assign random values to the instance of the course class
Course * assignRandom(Course* obj, int size){
int id;
double gpa;
for(int i = 0; i<size; i++){
id = (rand()%100)+1;
gpa = (rand()%5)+1;
gpa = gpa+(id/100.0);
obj->enroll(id, gpa);
}
return obj;
}
// Driver function
int main(){
Course *c1 = new Course(20);
Course *c2 = new Course(20);
Course *c3 = new Course(20);
Course *c4 = new Course(20);
Course *c5 = new Course(20);
c1 = assignRandom(c1, 20);
c1->print_info();
cout<<"\n";
c2 = assignRandom(c2, 20);
c2->print_info();
cout<<"\n";
c3 = assignRandom(c3, 20);
c3->print_info();
cout<<"\n";
c4 = assignRandom(c4, 20);
c4->print_info();
cout<<"\n";
c5 = assignRandom(c5, 20);
c5->print_info();
cout<<"\n";
// Calculating and printing overall GPA
double overAllGpa = (c1->getAverage()+ c2->getAverage() + c3->getAverage() + c4->getAverage() + c5->getAverage())/5;
cout<<"OverAll average GPA: "<<overAllGpa<<"\n";
return 0;
}