Calculate the Sum of Elements in an Array
Understanding Sum Calculation
Summing elements in an array involves adding all the elements together to get a total sum.
We will explore three different methods to calculate the sum of an array using C++.
Method 1: Using a Loop
This method iterates through the array and accumulates the sum.
#include <iostream> using namespace std; 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]; } cout << "Sum: " << sum; return 0; }
Method 2: Using Recursion
This method calculates the sum recursively.
#include <iostream> using namespace std; int sum_recursive(int arr[], int n) { if (n == 0) return 0; return arr[n - 1] + sum_recursive(arr, n - 1); } int main() { int arr[] = {1, 2, 3, 4, 5}; int n = sizeof(arr) / sizeof(arr[0]); cout << "Sum: " << sum_recursive(arr, n); return 0; }
Method 3: Using Array Traversal with Pointers
This method calculates the sum using pointers.
#include <iostream> using namespace std; int main() { int arr[] = {1, 2, 3, 4, 5}; int n = sizeof(arr) / sizeof(arr[0]); int sum = 0, *ptr; for(ptr = arr; ptr < arr + n; ptr++) { sum += *ptr; } cout << "Sum: " << sum; return 0; }