Skip to main content

Section 15.12 Case Study: Students - Part 2

We now have a way to turn data in strings into a Student struct. We still are missing code to read in from the file and also missing code to calculate the average. We can work on these parts in whatever order we like. To work on the calculations before reading from the file, we can create some test students in code and use them for calculations. Doing so would be a good idea in any case, as it allows us to verify the calculation logic independently of the file input logic.
We will start with the calculation logic.

Subsection 15.12.1 Calculating One Average

Eventually, we want to calculate the average for each student. But it will be easier to start with just calculating the average for a single student. If we build a function to do that work, we can then call that function with each of the students.
To calculate a studentโ€™s average, we need to add up all of their scores and then divide by the number of scores. A function to do that just needs a vector of doubles representing the scores:
Listing 15.12.1.
double calculateAverage(const vector<double>& scores) {
    double total = 0.0;
    for (double score : scores) {
        total += score;
    }
    return total / scores.size();
}
Note that function does not depend on the entire student struct, only the scores vector. By just giving the function the vector of doubles, instead of the entire student, we simplify the function and make it more reusable.

Checkpoint 15.12.1.

Given the function in Listingย 15.12.1, and assuming you have a student variable s, How would use calculate the studentโ€™s average and store it as a double called avg?
  • double avg = calculateAverage(s.scores);
  • double avg = s.calculateAverage();
  • calculateAverage is not a member function
  • calculateAverage(avg, s);
  • calculateAverage is a pure function that returns a result
  • double avg = calculateAverage(s);
  • calculateAverage takes just the studentโ€™s scores, not the entire student
  • calculateAverage(s.scores);
  • That does nothing with the average that is returned

Subsection 15.12.2 Calculating all the Averages

Now we want to calculate multiple averages and print them all. Because we are going to be printing the data, it will be hard to use doctest unit tests. Instead, we will simply run a program with some test data and examine the output to see if it looks correct.

Checkpoint 15.12.2.

main has code to build multiple students. Add code to loop through the students and print the first name and average score for each. Put each student on a separate line and use a single space between the name and score:
Hint.
If you are stuck, start by looping through the vector and just printing each first name. Accessing a first name should look something like s.name.first. Once that is working, use the calculateAverage function on each studentโ€™s scores.
You have attempted of activities on this page.