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>
#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;
}
Comments
Leave a comment