Answer to Question #294612 in C++ for Yaku

Question #294612

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).


1
Expert's answer
2022-02-08T09:35:31-0500
#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]<<" ";
	}	
}

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
New on Blog