Sum Of Array Elements Using Recursion
QUESTION DESCRIPTION :
Given an array of integer elements, find sum of array elements using recursion.
TEST CASE 1
INPUT
5
1 2 3 4 5
OUTPUT
15
TEST CASE 2
INPUT
4
4 4 4 4
OUTPUT
16
Given an array of integer elements, find sum of array elements using recursion.
TEST CASE 1
INPUT
5
1 2 3 4 5
OUTPUT
15
TEST CASE 2
INPUT
4
4 4 4 4
OUTPUT
16
#include<iostream> using namespace std; int add(int arr[],int n){ // this is a recursive function that returns the sum of the array if(n>=0){ return arr[n]+add(arr,n-1); // if n>=0 i.e. a valid index we return // the current array value to the old recursive call // and then make another recursive call with a smaller n value (n-1) } else{ return 0; // if all numbers have been added we return 0 and // don't make any recursive call thus exiting the function } } int main(){ int n; // to store the number of inputs; cin>>n; int arr[n]; // to store the n numbers for(int i=0;i<n;i++){ cin>>arr[i]; // taking the integers as input } cout<< add(arr,n-1); // directly printing the sum return 0; }
Problem Description
The task is to calculate the sum of the elements in an array using recursion. Given an array of integers, you need to write a recursive function to compute the sum of its elements.
Solution Approach
To solve this problem using recursion, you'll need to:
- Define a recursive function that calculates the sum of the array elements.
- Base the recursion on the idea of reducing the problem size step-by-step.
Explanation of the Code
Recursive Function
add
:
- Base Case: If
n
is less than 0, return 0. This indicates that we have processed all elements.- Recursive Case: If
n
is 0 or greater, return the current elementarr[n]
plus the result of the recursive calladd(arr, n - 1)
. This step processes the current element and then continues to process the rest of the array.Main Function:
- Input Handling: Reads the number of elements
n
, then readsn
integers into the arrayarr
.- Sum Calculation: Calls the
add
function with the last indexn - 1
of the array and prints the result.Edge Cases and Considerations
- Empty Array: If the number of elements
n
is 0, the function should handle this correctly, returning 0 as no elements are present to sum.- Large Arrays: Ensure that the recursion depth is manageable. C++ has a limit on recursion depth, and very large arrays might cause stack overflow.
Conclusion
The provided solution efficiently computes the sum of an array using recursion by breaking the problem into smaller subproblems and summing up the results. The base case ensures the recursion terminates correctly, and the main function handles input and output operations.