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.
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.