Skip to main content

Function template: sum and average of array

Short answer

Define function templates sum and average. sum accumulates elements, average returns (double)sum/n. For int array {10,20,30,40,50}, sum=150, average=30; for float array {1.5,2.5,3.5,4.5}, sum=12, average=3.

Write a program that will find the sum and average of elements in an array using function templates.

#include <iostream>
using namespace std;

template <class T>
T sum(T arr[], int n) {
    T total = 0;
    for (int i = 0; i < n; i++)
        total += arr[i];
    return total;
}

template <class T>
double average(T arr[], int n) {
    return (double)sum(arr, n) / n;
}

int main() {
    int a[5] = {10, 20, 30, 40, 50};
    float b[4] = {1.5f, 2.5f, 3.5f, 4.5f};

    cout << "Integer array: sum = " << sum(a, 5)
         << ", average = " << average(a, 5) << endl;
    cout << "Float array:   sum = " << sum(b, 4)
         << ", average = " << average(b, 4) << endl;
    return 0;
}

Output

Integer array: sum = 150, average = 30
Float array:   sum = 12, average = 3

The type T is deduced from the array argument, so the same functions work for int and float arrays. The average is returned as double so that integer arrays do not lose the fractional part.

✓ Answer checked by Claude Opus 5.5 (high effort)

All Object Oriented Programming chapter 9 questions →