Answer to Question #202657 in C++ for SONAM YENTEN

Question #202657

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-03T13:42:20-0400
#include <iostream>
using namespace std;
template<typename type>
type average(type arr[], int size){
    double sum = arr[0];
    for(int i = 1; i < size; i++) sum += arr[i];
    return (type)(sum / size);
}
int main(){
    int intarr[] = {1, 2, 3, 4, 5}, size = 5;
    cout<<"Integer: "<<average<int>(intarr, size);


    long longarr[] = {1, 2, 3, 4, 5};
    cout<<"\nLong: "<<average<long>(longarr, size);


    double doublearr[] = {1.0, 2.0, 3.0, 4.0, 5.0};
    cout<<"\nDouble: "<<average<double>(doublearr, size);


    char chararr[] = {'a', 'b', 'c', 'd', 'e'};
    cout<<"\nChar: "<<average<char>(chararr, size);


    return 0;
}

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