C Program to Calculate the Average of All Elements of an Array
Last Updated :
01 Jun, 2023
Given an array arr of size N, the task is to calculate the average of all the elements of the given array.
Example
Input: arr[] = {1, 2, 3, 4, 5}
Output: 3
Approach
1. We can simply find the sum of all elements of a given array.
2. 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
Pseudocode
procedure average(arr)
Declare sum as integer
FOR EACH value in arr DO
sum ← sum + arr[n]
END FOR
avg ← sum / size_of_array
Display avg
end procedure
Program to Calculate Average of All Elements of an Array
Below is the C program to implement the above approach:
C
#include <stdio.h>
double average( int a[], int n)
{
int sum = 0;
for ( int i = 0; i < n; i++)
sum += a[i];
return ( double )sum / n;
}
int main()
{
int arr[] = { 1, 2, 3, 4, 5 };
int n = sizeof (arr) / sizeof (arr[0]);
int avg = average(arr, n);
printf ( "Average = %d " , avg);
return 0;
}
|
The complexity of the above method
Time Complexity: O(n)
Space Complexity: O(1)
Share your thoughts in the comments
Please Login to comment...