Skip to content
Related Articles

Related Articles

C Program to Calculate the Average of All Elements of an Array

View Discussion
Improve Article
Save Article
  • Difficulty Level : Easy
  • Last Updated : 01 Aug, 2022
View Discussion
Improve Article
Save Article

Here, we will develop a C Program to Calculate the Average of All Elements of an Array:

Input:

arr[] = {1, 2, 3, 4, 5}

Output :

3

Approach

The approach is very simple for this program, We can simply find the sum of all elements of a given array and divide this sum by the total number of elements present in the array. 

  • Sum of the elements is = 1+2+3+4+5 = 15 
  • The total number of elements = 5.
  • Average = 15/5 = 3

Example:

C




// C program to demonstrate
// average of array elements
#include <stdio.h>
  
// Function that return average of given array.
double average(int a[], int n)
{
    // Find the sum of array element
    int sum = 0;
    for (int i = 0; i < n; i++)
        sum += a[i];
  
    return (double)sum / n;
}
  
// Driver code
int main()
{
    // input array
    int arr[] = { 1, 2, 3, 4, 5 };
  
    // size of array
    int n = sizeof(arr) / sizeof(arr[0]);
  
    // average(arr, n) function is return the average of the
    // array.
    int avg = average(arr, n);
  
    // display average of given array
    printf(" Average = %d ", avg);
    return 0;
}

Output

 Average = 3 

Time Complexity: O(n)

Space Complexity: O(1) 

My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!