Averaging an Array of Unknown Size

Imagine you’re working with an array that has room to store thousands of integer values. You’ve been hired to craft a function that averages those values, but you don’t really know how many values are stored in the array. The guy who gave you the assignment (me), simply said that the array is capped with a zero value.

In last week’s Lesson, I showed you how to mark the end of an array by capping it with a zero value. That’s an approach similar to the way character arrays (strings) work in the C language.

Once you know that an array is capped with a zero, you can manipulate the array’s elements and know exactly when they stop. In this week’s example code, I borrow the average() function from this month’s Exercise, modifying it to handle an int array capped with a zero value. (The core of the main() function is stolen from last week’s Lesson.)

#include <stdio.h>

#define MAX 10

int average(int *a);

int main()
{
    int number[MAX];
    int count,avg;

    count = 0;
    while(count < MAX)
    {
        printf("Type your favorite number, 0 to end: ");
        scanf("%d",&number[count]);
        if( number[count] == 0 )
            break;
        count++;
    }
    avg = average(number);
    printf("The average of those values is %d\n",avg);

    return(0);
}

int average(int *a)
{
    int x,total;

    x = total = 0;

    while(a[x])
    {
        total += a[x];
        x++;
    }
    return(total/x);
}

Does average() need to be an int function? Look at the return statement.

In this case, I coded the function to return an int value because integers are being processed. That's okay, but it's not going to be precise. My advice would be to calculate an average as a floating point value. In fact, the average() functions I've seen in other languages are defined as floating point.

An obvious question at this point would be, "What if you're averaging an array and zero is a valid value?"

The stock answer is, "Then you use the value -1, or any negative number, to cap the array." That happens a lot in C.

Then again, what if all values — the entire range for the variable type, negative to positive and zero — are allowed in the array?

In that case, a solution is still possible — but you have to cheat. I'll present that cheat in next week's Lesson.