Lesson 99 +35 XP

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_element and std::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

  1. Sum the scores: int sum = 0; then for (int score : grades) sum += score;.
  2. Guard the rest: only average when !grades.empty().
  3. Compute double avg = sum / (double)grades.size();.
  4. Find extremes with *min_element(grades.begin(), grades.end()) and the max_element twin.
  5. Print Average:, Min:, and Max: with labels.
  6. Test with 10 20 30 -1 and check the math by hand.

Checklist

  • [ ] Grades are stored in std::vector<int>
  • [ ] push_back adds each grade
  • [ ] A range-for loop sums the grades
  • [ ] The average is a double, not an int
  • [ ] min_element and max_element print the extremes
  • [ ] An empty list is handled instead of crashing

TL;DR

  • std::vector<int> grows as you push_back.
  • A range-for for (int x : v) visits every element.
  • Cast to (double) before dividing to keep the fraction.
  • min_element and max_element need <algorithm>.