Loading lessons...
Project 5: Grade Tracker with Arrays
Project 5: Grade Tracker with Arrays
You practiced arrays; now build a real tracker. Collect a list of exam grades and print the sum, average, lowest, and highest. Use std::vector - the smart choice - because the number of grades can change as you type them in.
The goal
Read a set of grades into a std::vector<int>, compute the average, and print the lowest and highest grade.
What you practice
- Using
std::vector<int>instead of a raw array - Adding entries with
push_back - A range-for loop to sum the scores
std::min_elementandstd::max_element
Starter code
This compiles as-is:
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
int main() {
vector<int> grades;
int g;
cout << "Enter grades, type -1 to finish:" << endl;
while (true) {
cin >> g;
if (g < 0) break;
grades.push_back(g);
}
cout << "You entered " << grades.size() << " grades." << endl;
return 0;
}
Step-by-step
- Sum the scores:
int sum = 0;thenfor (int score : grades) sum += score;. - Guard the rest: only average when
!grades.empty(). - Compute
double avg = sum / (double)grades.size();. - Find extremes with
*min_element(grades.begin(), grades.end())and themax_elementtwin. - Print
Average:,Min:, andMax:with labels. - Test with
10 20 30 -1and check the math by hand.
Checklist
- [ ] Grades are stored in
std::vector<int> - [ ]
push_backadds each grade - [ ] A range-for loop sums the grades
- [ ] The average is a
double, not anint - [ ]
min_elementandmax_elementprint the extremes - [ ] An empty list is handled instead of crashing
TL;DR
std::vector<int>grows as youpush_back.- A range-for
for (int x : v)visits every element. - Cast to
(double)before dividing to keep the fraction. min_elementandmax_elementneed<algorithm>.