Sum
#include <iostream>using namespace std;
int getSum(int *arr, int size) {
// Base case: If the size of the array is 0, return 0. if(size == 0) { return 0; // An empty array has a sum of 0. }
// Base case: If the size of the array is 1, return the first element. if(size == 1) { return arr[0]; // The sum of a single element array is the element itself. }
// Recursive case: Calculate the sum of the remaining elements. // Call getSum on the rest of the array (arr + 1) and reduce the size by 1 (size - 1). int remainingPart = getSum(arr + 1, size - 1);
// Calculate the total sum by adding the first element to the sum of the remaining part. int sum = arr[0] + remainingPart;
// Return the total sum. return sum;}
int main() { int arr[] = {1, 2, 3, 4, 5}; // Example array int size = sizeof(arr) / sizeof(arr[0]); // Calculate the size of the array
int totalSum = getSum(arr, size); // Call getSum to calculate the sum cout << "Sum of the array elements: " << totalSum << endl; // Output the result
return 0;}
Example Walkthrough:
Let’s calculate the sum of the array arr[] = {1, 2, 3, 4, 5}
with size = 5
:
-
First Call:
getSum(arr, 5)
- Size is not 0 or 1, so it makes a recursive call:
remainingPart = getSum(arr + 1, 4)
.
- Size is not 0 or 1, so it makes a recursive call:
-
Second Call:
getSum(arr + 1, 4)
(now considering{2, 3, 4, 5}
)- Size is
4
, so it calls:remainingPart = getSum(arr + 1, 3)
.
- Size is
-
Third Call:
getSum(arr + 2, 3)
(now considering{3, 4, 5}
)- Size is
3
, so it calls:remainingPart = getSum(arr + 1, 2)
.
- Size is
-
Fourth Call:
getSum(arr + 3, 2)
(now considering{4, 5}
)- Size is
2
, so it calls:remainingPart = getSum(arr + 1, 1)
.
- Size is
-
Fifth Call:
getSum(arr + 4, 1)
(now considering{5}
)- Size is
1
, so it returnsarr[0]
which is5
.
- Size is
Now the recursion starts unwinding:
- Returning to Fourth Call:
remainingPart = 5
sum = 4 + 5 = 9
- Return 9.
- Returning to Third Call:
remainingPart = 9
sum = 3 + 9 = 12
- Return 12.
- Returning to Second Call:
remainingPart = 12
sum = 2 + 12 = 14
- Return 14.
- Returning to First Call:
remainingPart = 14
sum = 1 + 14 = 15
- Return 15
Final Output:
Sum of the array elements: 15