Calculate the Sum of Elements in an Array
Understanding Sum Calculation
Finding the sum of elements in an array involves adding all elements together.
We will explore three different methods to determine the sum using C++.
Method 1: Using a Loop
This method iterates through the array and calculates the sum.
#include <iostream> using namespace std; int findSum(int arr[], int n) { int sum = 0; for (int i = 0; i < n; i++) { sum += arr[i]; } return sum; } int main() { int arr[] = {1, 2, 3, 4, 5}; int n = 5; cout << "Sum: " << findSum(arr, n) << endl; return 0; }
Sum: 15
Method 2: Using Recursion
This method calculates the sum recursively.
#include <iostream> using namespace std; int findSum(int arr[], int n) { if (n == 0) return 0; return arr[n - 1] + findSum(arr, n - 1); } int main() { int arr[] = {1, 2, 3, 4, 5}; int n = 5; cout << "Sum: " << findSum(arr, n) << endl; return 0; }
Sum: 15
Method 3: Using STL Accumulate
This method uses the accumulate function from the STL.
#include <iostream> #include <numeric> using namespace std; int main() { int arr[] = {1, 2, 3, 4, 5}; int n = 5; int sum = accumulate(arr, arr + n, 0); cout << "Sum: " << sum << endl; return 0; }
Sum: 15