Answer to Question #202287 in C++ for Namish

Question #202287

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 int, long, double, 

and char


1
Expert's answer
2021-06-02T13:14:16-0400
#include <iostream>


using namespace std;


template <typename T>
double calculateAverage(T values[], int n){
	double total = 0;
	for (int i = 0; i < n; i++){
		total += values[i];
	}
	return total/n;
}
int main(){
	int size =5;
	int intValues[] = {10, 10, 12, 445, 1};
	double doubleValues[] = {1.5, 23.48, 41.89, 11.85,2.326};
	long longValues[] = {13246, 222, 355, 7575,3333};
	char charValues[] = {'l', 'u', 'q', 'z', 'p'};


	cout << "Average of integers: " << calculateAverage<int>(intValues, size) << "\n"; 
	cout << "Average of doubles: " << calculateAverage<double>(doubleValues, size) << "\n"; 
	cout << "Average of long: " << calculateAverage<long>(longValues, size) << "\n";
	cout << "Average of chars: " << calculateAverage<char>(charValues, size) << "\n";


	system("pause");
}

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