Recursive Average

Problem

Write a recursive algorithm to compute the average of an array of numbers.

Recursive Exponential Function

Solution

The average of an array of numbers is the sum of all numbers divided by the total number of elements. It is the same as dividing each number by the total number of elements then adding each division result to get the final average value. For example Avg(A) = (A[0] + … + A[n-1])/n = A[0]/n + … + A[n-1]/n As you can see it is almost the same formula as the recursive sum problem that we solved before except we are dividing by (n)

Recursive Average Algorithm

Here is the code in C++

Solution

We can compute the average recursively using the concept of running average. If we have already calculated the average of some elements then the average when adding one more element to the list is calculated by adding the element to the product of the old average with number of elements before addition divided by the current total number of elements

Code

Here is the code in C++

Thanks for visiting.

Add a Comment

Your email address will not be published. Required fields are marked *