The average of an array is calculated by dividing the sum of all its elements by the total number of elements.
- It can be calculated using iterative or recursive approaches.
- The result should generally be stored in a floating-point type to handle non-integer averages.
Examples:
Input: arr[] = {1, 2, 3, 4, 5}
Output: 3Explanation: The sum is 15 and the number of elements is 5, so the average is 15 / 5 = 3.
Input: arr[] = {10, 20, 30, 40}
Output: 25Explanation: The sum is 100 and the number of elements is 4, so the average is 100 / 4 = 25.
Iterative Approach
The iterative approach traverses the array, calculates the sum of its elements, and divides the sum by the array size.
Steps:
- Initialize a variable to store the sum.
- Traverse the array and add each element to the sum.
- Divide the sum by the number of elements.
- Return the resulting average.
#include <iostream>
using namespace std;
// Function to find average of an array
double average(int arr[], int n)
{
if (n == 0)
return 0;
long long sum = 0;
for (int i = 0; i < n; i++)
sum += arr[i];
return static_cast<double>(sum) / n;
}
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
Explanation
- The average() function traverses all elements and calculates their sum.
- The sum is divided by n, the number of elements.
- static_cast<double> ensures that the division produces a floating-point result when required.
Recursive Approach
The recursive approach calculates the sum of the array elements recursively and divides the final sum by the number of elements.
Steps:
- Start from the first element of the array.
- Recursively calculate the sum of the remaining elements.
- Add the current element to the returned sum.
- Divide the total sum by the number of elements.
#include <iostream>
using namespace std;
// Recursively calculates the sum
long long sumRec(int arr[], int i, int n)
{
if (i == n)
return 0;
return arr[i] + sumRec(arr, i + 1, n);
}
// Function to find average of an array
double average(int arr[], int n)
{
if (n == 0)
return 0;
return static_cast<double>(sumRec(arr, 0, n)) / n;
}
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
Explanation
- sumRec() recursively visits each array element and adds it to the sum.
- The recursion stops when i reaches n.
- The total sum is then divided by the number of elements to obtain the average.