Given an array, the task is to find the average of that array. Average is the sum of the array elements divided by the number of elements. For Example:
Input: arr[] = {1, 2, 3, 4, 5}
Output: 3
- Sum of the elements is 1+2+3+4+5 = 15
- and total number of elements is 5.
- So average is 15/5 = 3
Below are different approaches:
Iterative Approach
- Iterate each element of an array using a loop.
- Sum up each element of the array till we reach the end of the array.
- Divide the sum by the total number of elements and return the average.
#include <iostream>
using namespace std;
// Function that return average
// of an array.
double average(int a[], int n)
{
if (n == 0)
return 0; // handle empty array
int sum = 0;
for (int i = 0; i < n; i++)
sum += a[i];
return (double)sum / n;
}
// Driver code
int main()
{
int arr[] = { 10, 2, 3, 4, 5, 6, 7, 8, 9 };
int n = sizeof(arr) / sizeof(arr[0]);
cout << average(arr, n) << endl;
return 0;
}
Output
6
- Time Complexity: O(n), The time complexity of the above code is O(n) as it loops through all elements of the array to calculate the sum.
- Auxiliary Space: O(1), The space complexity is O(1) as no extra space is used.
Recursive Approach
- We will call the function again and again till we reach the end of an array.
- We will sum every element of the array and when we reach the end of an array, we will return the average of the array.
#include <iostream>
using namespace std;
// Recursively computes average
// of a[]
double avgRec(int a[], int i, int n)
{
// Last element
if (i == n - 1)
return a[i];
// When index is 0, divide sum
// computed so far by n.
if (i == 0)
return ((a[i] + avgRec(a, i + 1, n)) / n);
// Compute sum
return (a[i] + avgRec(a, i + 1, n));
}
// Function that return average
// of an array.
double average(int a[], int n) {
if (n == 0)
return 0; // handle empty array
return avgRec(a, 0, n);
}
// Driver code
int main()
{
int arr[] = { 10, 2, 3, 4, 5, 6, 7, 8, 9 };
int n = sizeof(arr) / sizeof(arr[0]);
cout << average(arr, n) << endl;
return 0;
}