Just Average – Solution

If you attempted to compile the code skeleton for this month’s Exercise, you most likely stumbled across the first problem to solve: The average() function requires a type.

Before I get into my explanation, click here to view my solution to the “Just Average” Exercise.

In the Exercise post, I purposefully omitted the function’s type to drive home a point about calculating the average of a series of numbers: Numeric values in the C language can be either integers or real (floating point). The average() function must deal with floating point values, so I cast it as a float in my solution, shown at Line 5:

#include <stdio.h>

#define COUNT 10

float average(float *a, int size);

Above, you also see the second required addition, the average() function’s two arguments: The array to be averaged and the size of that array. Arrays are pointers in disguise, which is why pointer notation is used above. And even though the array is a float, its size (the number of elements) is an int.

Because a program can’t determine an array’s size on-the-fly, any average() function must somehow know the array’s size or, specifically, its ending point. In my solution, that value is passed directly to the function.

The rest of the main() function was provided in the Exercise. My only addition is the printf() function you see below at Line 17, which displays the result and calls the average() function:

int main()
{
    float scores[COUNT] = {
        97.2, 86.0, 75.5, 93.2, 87.1,
        68.7, 81.9, 92.4, 84.0, 66.3 };
    int x;

    for(x=0;x<COUNT;x++)
        printf("Student %2d score %3.1f\n",x+1,scores[x]);
    /* display average score */
    printf("Average score = %.1f\n",average(scores,COUNT));

    return(0);
}

The average of a series of values is calculated by taking the sum of those values and then dividing it by the number of values.

float average(float *a, int size)
{
    int x;
    float total = 0.0;

    for(x=0;x<size;x++)
        total += a[x];
    return(total/size);
}

The total variable acts as an accumulator. It’s initialized to zero (actually 0.0, which is a floating point value), then it keeps adding to itself (in Line 28) each element’s value from the array. That total is divided by the size value, with the result — the average — returned from the function.