Information about cookies on this page

Our website uses cookies to ensure the functionality of the website, to collect and analyze information about the performance and usage of the website. Privacy Policy

  • Courses
    • Discord
    • Twitter
    • Linkedin
    • Facebook
    • Instagram
  • Pricing
  • English
  • Čeština
  • Deutsch
  • Русский
Sign inStart free
  • Courses
  • Pricing

Community

Sign in
  
  • Courses
    • Discord
    • Twitter
    • Linkedin
    • Facebook
    • Instagram
  • Pricing
  • English
  • Čeština
  • Deutsch
  • Русский
Sign inStart free
  • Courses
  • Pricing

Community

Sign in

Class Average

The teacher wants to know how the test went overall: how many points the students got on average. The average is the sum of the scores divided by the number of students. The sum is the pattern from the lesson on loops: a variable that starts at 0, and a loop that adds each value to it. Here, the loop goes through the students as const references, as in printResults(), and adds each student.score.

A new function, average(), will compute it. It gets the vector as a const std::vector<Student>&, just like printResults(): without a copy, and only for reading. It returns a decimal number, so its type is double.

Watch out for integer division. When you divide a whole number by a whole number, C++ throws away the remainder, and the result is a whole number again: 7 / 2 is 3. A sum stored in an int variable and divided by students.size() would give 33 instead of 33.8. You get a decimal result when at least one of the numbers is a decimal (7.0 / 2 is 3.5). The easiest way is to add the values up in a double variable right away:

std::vector<int> temperatures = {18, 21, 23, 19};
double sum = 0;
for (int t : temperatures) {
    sum += t;
}
std::cout << "Average temperature: " << sum / temperatures.size() << std::endl;
Average temperature: 20.25

One more trap: return belongs after the loop. Inside the loop, it would end the function in the very first pass, and the average would be computed from the first student's score only.

Instructions

  1. 1

    Between grade() and printResults(), write a function double average(const std::vector<Student>& students) that adds up the scores of all the students and returns the sum divided by their number.

  2. 2

    At the end of printResults(), after the loop (not inside it), print the average computed by average(). A new line appears under the students' results:

    Average score: 33.8

    If you see 33, you're adding up in an int variable. If you see 8.4, the return is inside the loop.

Back

3/8

  1. 1. Test Results
  2. 2. Grades
  3. 3. Class Average
  4. 4. Top Score
  5. 5. Ranking
  6. 6. Bonus Points
  7. 7. Finding a Student
  8. 8. Congratulations!
Next

Try it yourself

Do this exercise right here in your browser. No account needed.