Program to Calculate Average of All Elements of an Array
Below is the C program to implement the above approach:
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
The complexity of the above method
Time Complexity: O(n)
Space Complexity: O(1)
C Program to Calculate the Average of All Elements of an Array
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