Answer to Question #287543 in C++ for amna

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.


1
Expert's answer
2022-01-14T13:46:23-0500
#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;
}

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