Problem: Calculating the Average and Sum of Array Elements

Problem

We want to create a function called average_sum.

This function has a return type of void and takes the following parameters as input:

  • An array a of type double with the values to operate on;
  • An integer n containing the number of elements in the array;
  • A pointer to a double that will contain the average of the array elements: average;
  • A pointer to a double that will contain the sum of the array elements: sum.

The function signature will be:

void average_sum(double a[], int n, double *average, double *sum);

Implementation

Let's try to implement the function.

From the requirements described above, the function uses two pointers to return the sum and average results of the array.

A possible implementation is the following:

void average_sum(double a[], int n, double *average, double *sum) {
    int i;

    /* Initialize the sum to the first element of the array */
    *sum = a[0];

    for (i = 1; i < n; ++i) {
        *sum += a[i];
    }

    *average = *sum / ((double) n);
}

Note that we have optimized the implementation since the average is equal to the sum divided by the number of elements in the array. Therefore, the sum is calculated only once while the average is calculated only after the loop.

Complete Program

Let's now try to write a complete program that reads 10 double values from the console and calculates their sum and average.

#include <stdio.h>

void average_sum(double a[], int n, double *average, double *sum);

int main() {
    const int n = 10;
    int i;

    double a[n];

    double average, sum;

    /* Read the values from keyboard */
    for (i = 0; i < n; ++i) {
        printf("Enter the %d° value: ", i + 1);
        scanf("%lf", &a[i]);
    }

    /* Calculate the average and the sum */
    average_sum(a, n, &average, &sum);

    /* Print the results */
    printf("The average is: %f\n", average);
    printf("The sum is: %f\n", sum);

    return 0;
}

void average_sum(double a[], int n, double *average, double *sum) {
    int i;

    /* Initialize the sum to the first element of the array */
    *sum = a[0];

    for (i = 1; i < n; ++i) {
        *sum += a[i];
    }

    *average = *sum / ((double) n);
}

A possible execution of the program is the following:

Enter the 1° value: 3.2
Enter the 2° value: 1.2
Enter the 3° value: 3.5
Enter the 4° value: 6.7
Enter the 5° value: 8.2
Enter the 6° value: 5.6
Enter the 7° value: 4.22
Enter the 8° value: 5.1
Enter the 9° value: 5.2
Enter the 10° value: 9.4
The average is: 5.232000
The sum is: 52.320000