![]() |
VOOZH | about |
Given an array arr[] of integers, calculate the mean (average) using recursion.
Note: The mean of an array is the sum of its elements divided by the number of elements in the array.
Examples:
Input: arr[] = [1, 2, 3, 4, 5]
Output: 3
Explanation: The sum of elements (15) divided by the number of elements (5) gives the mean: 3Input: arr[] = [1, 2, 3]
Output: 2
Explanation: The sum of elements (6) divided by the number of elements (3) gives the mean: 2
The idea is to compute the mean recursively by building it from smaller prefixes of the array.
Let mean(arr, n) represent the mean of the first n elements. We first calculate the mean of the first nā1 elements recursively. Since the mean of nā1 elements equals their sum divided by (nā1), multiplying it by (nā1) gives their total sum. We then add the nth element arr[nā1] to this sum and divide the result by n to obtain the mean of the first n elements.
The recursive formula for calculating the mean of an array is:
3