Search⌘ K

Solution: Finding the Array Sum

Explore how to implement a function template in C++ to calculate the sum of elements in an array. Learn to define template functions, loop through array elements, and apply these concepts practically to print the sum for different arrays.

Finding the array sum using templates

Let’s first execute the following solutions to find the array sum using templates and see the code output. Then we’ll go through it line by line.

C++
#include <iostream>
template<typename T>
T arrSum(const T* arr, int arrSize)
{
T result = 0;
for (int i = 0; i < arrSize; i++) {
result += arr[i];
}
return result;
}
int main()
{
// Array declarations
int intArray[] = {1, 2, 3, 4, 5};
float floatArray[] = {1.5, 2.5, 3.5, 4.5, 5.5};
double doubleArray[] = {4.75, 5.91234, 10.101010, 0.0001, 9.151515};
int intArraySize, floatArraySize, doubleArraySize = 0;
// Finding the size of each array
intArraySize = sizeof(doubleArray) / sizeof(doubleArray[0]);
floatArraySize = sizeof(doubleArray) / sizeof(doubleArray[0]);
doubleArraySize = sizeof(doubleArray) / sizeof(doubleArray[0]);
// Printing results to the console
std::cout << "Sum of integers: " << arrSum(intArray, intArraySize) << std::endl;
std::cout << "Sum of floating-point numbers: " << arrSum(floatArray, floatArraySize) << std::endl;
std::cout << "Sum of double numbers: " << arrSum(doubleArray, doubleArraySize) << std::endl;
}

Explan

...