Answer to Question #208711 in C++ for SimpNick

Question #208711

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-20T08:11:15-0400
#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;
}

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
APPROVED BY CLIENTS