Consider the process of taking the average of a list of N (real) numbers. The list will be contained in an array, X, of real numbers. The numbers will be referenced as X[0], X[1], X[2], ..., X[N-1].
a) Prove that the process of taking the average of a list of N real numbers is recursive.
Hint: Use function polymorphism.
b) As a result of a) above or otherwise, write the corresponding polymorphic and
recursive C++ function that computes the average of a list of N numbers.
#include<iostream>
using namespace std;
double AverageOfList(int* arr, int N)
{
static double res=0;
static int count=N;
if(N>0)
{
res+=arr[N-1];
return AverageOfList(arr,N-1);
}
return res/count;
}
int main()
{
int arr[]={5,8,11,16,25,4,7,9,11,15};
int n=sizeof(arr)/sizeof(int);
cout<<"Average of a list of "<<n<<" is ";
cout<<AverageOfList(arr,n);
}
Comments
Leave a comment