Answer to Question #202210 in C++ for Rask

Question #202210

Write a template function that returns the average of all the elements of an array. The arguments to the function should be the array name and the size of the array (type int). In main(), exercise the function with arrays of type intlongdouble, and char.


1
Expert's answer
2021-06-02T16:25:02-0400
#include<iostream>
#include<array>
using namespace std;
template <typename P>
// The average function template
P average(array<P, 3>arr){
	double sum = 0.0;
	for(auto x: arr){
		sum += x;
	}
	return sum / 3;
}




int main(){
	//To demostrate that the function template works with the arrays of type double
	double result1;
	array<double, 3> marks{60.9002783, 78.87373873, 90.667663767};
	result1 = average<double> (marks);
	cout<<"The average is: \t"<<result1<<endl;
	
		//To demostrate that the function template works with the arrays of type int
	array<int, 3> marks1{61, 79, 92};
	int result2;
	result2 = average<int> (marks1);
	cout<<"The average is: \t"<<result2<<endl;
	
	//	//To demostrate that the function template works with the arrays of type char
	array<char, 3> marks3{'A','B', 'C'};
	char result3;
	result3 = average<char> (marks3);
	cout<<"The average is: \t"<<result3<<endl;
	//	//To demostrate that the function template works with the arrays of type long
	long creditCardNumber = 1234567890123456L;
long socialSecurityNumber = 999999999L;
long hexBytes = 0xFFECDE5E;
long results4;
	array<long, 3> marks4{creditCardNumber, socialSecurityNumber,  hexBytes};
		results4 = average<long> (marks4);
	cout<<"The average is: \t"<<results4<<endl;


	
	
}

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