Todd Seller
Todd Seller

Reputation: 13

How can I make this function more modular and be used for multiple members of a struct?

I am trying to learn C and I am having trouble writing a function for a project I am working on for class. I need to find the average of 7 different scores that I read in from a file and split into members of a structure. The problem I am having is I can't seem to figure out a way to write a modular function so I can use the different members of the structure. I am including the structure as well as the function and prototype I have written. Any suggestions would be greatly appreciated as I have searched and searched and couldn't seem to find anything that would help.

My Structure:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#define MAXNAME         50
#define MAXSTUDENTS     100

int count;

typedef struct {

    char  name[MAXNAME];
    float quiz1;
    float quiz2;
    float quiz3;
    float quiz4;
    float midTerm1;
    float midTerm2;
    float final;
    float totalScore;
    char  finalGpa;

}student;

My Prototype:

float averageQuiz1(int count, student *dataList);

My Function:

float averageQuiz1(int count, student *dataList)
{
int i;
float total = 0;

for (i = 0; i < count; i++) {

    total += dataList[i].quiz1;

}
return total/count;
}

Again, any help in pointing me in the right direction to make this modular so I can replace dataList[i].quiz with another member of the structure would be greatly appreciated.

Upvotes: 1

Views: 61

Answers (1)

Paul R
Paul R

Reputation: 213170

You will have much more flexibility if you change your struct so that all the scores are in an array, e.g.

typedef enum { // define a new enum to select which score you're working with 
    quiz1,
    quiz2,
    quiz3,
    quiz4,
    midTerm1,
    midTerm2,
    final,
    totalScore,
    NUM_SCORES
} Score;

typedef struct {
    char  name[MAXNAME];
    float scores[NUM_SCORES]; // array of scores
    char  finalGpa;
} student;

Then you could have a general purpose averageQuiz function where you specify which score you want to calculate the average for:

float averageQuiz(int count, student *dataList, Score s)
{
    int i;
    float total = 0;
    float average = 0;

    for (i = 0; i < count; i++) {
        total += dataList[i].scores[s]; // <<< note that we are summing score `s` here
    }
    average = total/count; // <<< bug fix from @user2722968
    return average;
}

and you would then call this as e.g.

averageScore = averageQuiz(count, dataList, quiz1);

Upvotes: 2

Related Questions