Using each class member in a single function to calculate the average

advertisements

I have a class with 4 test scores. Test1 - Test4. I want to create a function called mean that will compute the average of each exam in the course and store it in the mean array. But i can't seem to accomplish this through a single loop:

class Cstudent
{
public:
    string firstName, lastName;
    int test1, test2, test3, test4;
    float average;
};

/* Here is the problem, the next time i go through the loop, i want to store the sum of
test2 in to sum[1] after already storing the total in to sum[0] for test 1 */

float mean(Cstudent section[], int n)
{
    int sum[NUMBEROFEXAMS];
    float mean[NUMBEROFEXAMS];
    for(int i = 0; i < NUMBEROFEXAMS; i++)
        for(int j = 0; j < n; j++){
            sum[i] += section[j].test1;
        }

}


It would be easier to store the scores in an array:

#include <array>

class Student
{
public:
    string firstName, lastName;
    std::array<int, 4> test;
    float average;
};

Then you can easily get the average:

#include <algorithm> // for std::accumulate

Student s = ....;
...
float avg = std::accumulate(s.test.begin(), s.test.end(), 1.0)/s.test.size();