Write a program that calculates the GPA of a subject by using classes. Program should be able to add, delete, modify and View the Record.
#include <vector>
#include <iostream>
#include <string>
#include <iomanip>
using namespace std;
class GPA
{
public:
GPA() { gpa = 0; }
double GetGPA() { return gpa; }
void AddRecord(string name, int mark);
void DisplayRecords();
void EraseRecord(string name);
void ModifyRecord(string name, int mark);
private:
vector<pair<string, int>> marks;
double gpa;
void CalculateGPA();
};
void GPA::AddRecord(string name, int mark)
{
pair<string, int> temp(name, mark);
marks.push_back(temp);
CalculateGPA();
}
void GPA::DisplayRecords()
{
for (int i = 0; i < marks.size(); i++)
{
cout << marks[i].first << " " << marks[i].second << endl;
}
}
void GPA::EraseRecord(string name)
{
for (int i = 0; i < marks.size(); i++)
{
if (marks[i].first == name) marks.erase(marks.begin() + i);
}
CalculateGPA();
}
void GPA::ModifyRecord(string name, int mark)
{
for (int i = 0; i < marks.size(); i++)
{
if (marks[i].first == name)
{
marks[i].second = mark;
}
}
CalculateGPA();
}
void GPA::CalculateGPA()
{
double sum = 0;
for (int i = 0; i < marks.size(); i++)
{
sum += marks[i].second;
}
gpa = sum / marks.size();
}
int main()
{
cout << fixed << setprecision(2);
GPA myGPA;
myGPA.AddRecord("math", 96);
myGPA.AddRecord("chem", 65);
myGPA.DisplayRecords();
cout << "GPA is: " << myGPA.GetGPA() << endl;
myGPA.ModifyRecord("chem", 78);
myGPA.DisplayRecords();
cout << "GPA is: " << myGPA.GetGPA() << endl;
myGPA.EraseRecord("math");
myGPA.DisplayRecords();
cout << "GPA is: " << myGPA.GetGPA() << endl;
system("pause");
return 0;
}
Comments
Leave a comment