Open In App

C Program to Calculate Average of an Array

Last Updated : 21 Nov, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

In this article, we will learn how to calculate the average of all elements of an array using a C program.

The simplest method to calculate the average of all elements of an array is by using a loop. Let’s take a look at an example:

C
#include <stdio.h>

float getAvg(int arr[], int n) {
    int sum = 0;

    // Find the sum of all elements
    for (int i = 0; i < n; i++) {
        sum += arr[i];
    }
  	
  	// Return the average
    return (float)sum / n;
}

int main() {
    int arr[] = {1, 2, 3, 4, 5};
    int n = sizeof(arr) / sizeof(arr[0]);

  	// Calculate the average of array arr
    float res = getAvg(arr, n);  
  	
    printf("%.2f\n", res);
    return 0;
}

Output
3.00

Explanation: This method iterates through the entire array to find the sum of all elements and then divides the sum by the total number of elements to calculate the average.

This approach can also be implemented using recursion as shown below.

Using Recursion

This method computes the average of the first n-1 elements using a recursive call for each element of the array. Then it combines it with the average of last element to find the overall average.

C
#include <stdio.h>

float getAvg(int arr[], int n) {
    
    // If only one element left, return it
    if (n == 1) {
        return arr[0];
    }
  
    // Add the current element to the average of
  	// the remaining array
    return (arr[n - 1] + (n - 1) *
            getAvg(arr, n - 1)) / n; 
}

int main() {
    int arr[] = {1, 2, 3, 4, 5};
    int n = sizeof(arr) / sizeof(arr[0]);

    // Calculate the average
    float res = getAvg(arr, n);

    printf("%.2f", res);

    return 0;
}

Output
3.00


Next Article

Similar Reads