Text of Example Program

Select the program text below and paste it into a file.

/* "average.c" */

#include <stdio.h>

#define num   10
#define first 0
#define last  num-1

static int my_list[num] = {3,4,2,0,2,1,8,3,6,7};

int sum(int list[], int low, int high)
{
    int i, s = 0;
    for (i = low; i <= high; i++)
        s += list[i];
    return(s);
}

void print_average(int list[], int low, int high)
{
    int total, num_elements, average;
    total = sum(list, low, high);
    num_elements = high - low;  /* note this is an off-by-one bug */

    average = total / num_elements;
    printf("%10.d\n", average);
}

int main(void)
{
    /* Try two test cases. */
    print_average (my_list, first, last);
    print_average (my_list, first, last - 3);
}

Back to tutorial