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.
#include <iostream>
template<typename T>
T average(const T* data, int size)
{
T sum = data[0];
for(int i = 1; i < size; ++i)
{
sum += data[i];
}
return sum / size;
}
int main()
{
const int ARRAY_SIZE = 5;
int arrInts [ARRAY_SIZE] = {1, 2, 3, 4, 5};
long arrLongs [ARRAY_SIZE] = {1L, 2L, 3L, 4L, 5L};
double arrDoubles[ARRAY_SIZE] = {1.0, 2.0, 3.0, 4.0, 5.0};
char arrChars [ARRAY_SIZE] = {0x01, 0x02, 0x03, 0x04, 0x05};
std::cout << "Average of arrInts: " << average(arrInts, ARRAY_SIZE) << "\n";
std::cout << "Average of arrLongs: " << average(arrLongs, ARRAY_SIZE) << "\n";
std::cout << "Average of arrDoubles: " << average(arrDoubles, ARRAY_SIZE) << "\n";
std::cout << "Average of arrChars: " << static_cast<int>(average(arrChars, ARRAY_SIZE)) << "\n";
return 0;
}
Comments
Leave a comment