Question #287543

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.


Expert's answer

#include <iostream>
using namespace std;
template<typename type>
type average(type array[], int size){
    type sum = array[0];
    for(int i = 1; i < size; i++){
        sum += array[i];
    }
        cout<<sum<<endl;


    return (type) (sum / size);
}


int main(){
    char array1[] = {'a', 'b', 'c', 'd', 'e', 'f'};
    int array2[] = {1, 2, 3, 4, 5, 6}, size = 6;
    long array3[] = {1, 2, 3, 4, 5, 6};
    double array4[] = {1, 2, 3, 4, 5, 6};


    cout<<"int : "<<average<int>(array2, size);
    cout<<"\nlong : "<<average<long>(array3, size);
    cout<<"\ndouble : "<<average<double>(array4, size);
    cout<<"\nchar : "<<average<char>(array1, size);


    return 0;
}
LATEST TUTORIALS
APPROVED BY CLIENTS