C++ Array Sum Algorithm
This article will explain how to calculate the sum of all elements in a C++ array using different algorithms.
1. Simple Iteration Algorithm
This is the most straightforward and widely used method. We iterate through each element of the array, adding it to a running sum variable.
#include
int main() {
int arr[] = {1, 2, 3, 4, 5};
int n = sizeof(arr) / sizeof(arr[0]);
int sum = 0;
for (int i = 0; i < n; ++i) {
sum += arr[i];
}
std::cout << "Sum of array elements: " << sum << std::endl;
return 0;
}
In this code:
arr
is our array containing the elements.n
calculates the number of elements in the array.sum
is initialized to 0 to store the running sum.- The
for
loop iterates through the array, adding each element tosum
. - Finally, the calculated
sum
is printed.
2. Using std::accumulate
The C++ Standard Template Library (STL) provides a powerful function, std::accumulate
, specifically designed for calculating sums.
#include
#include
int main() {
int arr[] = {1, 2, 3, 4, 5};
int sum = std::accumulate(std::begin(arr), std::end(arr), 0);
std::cout << "Sum of array elements: " << sum << std::endl;
return 0;
}
Here:
- We include the
<numeric>
header for thestd::accumulate
function. std::begin(arr)
andstd::end(arr)
return iterators to the beginning and end of the array, respectively.0
is the initial value of the sum.
3. Recursive Approach
We can calculate the sum recursively by breaking the problem into smaller subproblems.
#include
int sum_array(int arr[], int n) {
if (n == 0) {
return 0;
}
return arr[n - 1] + sum_array(arr, n - 1);
}
int main() {
int arr[] = {1, 2, 3, 4, 5};
int n = sizeof(arr) / sizeof(arr[0]);
int sum = sum_array(arr, n);
std::cout << "Sum of array elements: " << sum << std::endl;
return 0;
}
In this code:
sum_array
is a recursive function that takes the array and its size as arguments.- The base case is when the array size
n
is 0, returning 0. - Otherwise, it returns the sum of the last element
arr[n-1]
and the recursive call tosum_array
with the rest of the array.
Conclusion
This article provides different approaches to calculating the sum of elements in a C++ array. Choose the method that best suits your needs and coding style. The STL's std::accumulate
is a convenient option, but understanding the iterative and recursive methods is valuable for improving your understanding of algorithms and programming fundamentals.