- 2070 Asar · 6 marks
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)
Related questions
- Array class template with max, min, sort · Object Oriented Programming, chapter 9
- Function overloading; new/delete average program · Object Oriented Programming, chapter 3
- Class and function template with syntax · Object Oriented Programming, chapter 9 · asked 4×
- Importance of function template · Object Oriented Programming, chapter 9 · asked 2×
- Need of template; function template overloading · Object Oriented Programming, chapter 9
- Function template power(base, exp) · Object Oriented Programming, chapter 9
- Correct program: case array and average · Computer Programming, chapter 3
- Sum and average until 0 is entered · Computer Programming, chapter 5
- Sum and average between M and N using pointer · Computer Programming, chapter 9
- GOTO types; sum of series program · Computer Programming, chapter 11