We have discussed iterative solution in this Post Sum of elements in a given array. In this Post we will discuss a recursive Solution.
Approach:
Illustration:
Given A = [1, 2, 3, 4, 5], the problem is solved recursively by breaking it down step by step. Each step reduces the array size, summing the last element with the sum of the remaining elements until the base case is reached.
# Function to calculate the sum of an array recursivelydefRecSum(arr,n):ifn<=0:return0returnRecSum(arr,n-1)+arr[n-1]defarraysum(arr):returnRecSum(arr,len(arr))# Driver codearr=[1,2,3,4,5]print(arraysum(arr))
// Function to calculate the sum of an array recursivelyfunctionRecSum(arr,n){if(n<=0)return0;returnRecSum(arr,n-1)+arr[n-1];}functionarraysum(arr){returnRecSum(arr,arr.length);}// Driver codeletarr=[1,2,3,4,5];console.log(arraysum(arr));
Output
15
Time Complexity: O(N), where N is the length of the array. Auxiliary Space: O(N), due to recursive function calls stored in the call stack.