Consider a list of (real) numbers, X, of length N. Squaring each number in the list is a recursive process. Prove this by writing a polymorphic and recursive C++ function
template <class Type>
Type * square (Type * X, long int N)
{
// C++ code
}
which recursively squares each element in X and returns that list (i.e. X with
elements squared).
#include<iostream>
using namespace std;
template<class Type>
Type* square(Type* X, long int N)
{
if(N>=0)
{
X[N]*=X[N];
return square(X,N-1);
}
}
int main()
{
int arr[]={5,8,11,16,25,4};
cout<<"Primary Array:\n";
for(int i=0;i<sizeof(arr)/sizeof(int);i++)
{
cout<<arr[i]<<" ";
}
//Recursive call function square
square<int>(arr,sizeof(arr)/sizeof(int));
cout<<"\nResulting Array:\n";
for(int i=0;i<sizeof(arr)/sizeof(int);i++)
{
cout<<arr[i]<<" ";
}
}
Comments
Leave a comment