Sum of array elements using recursion (original) (raw)
Last Updated : 17 Mar, 2025
Given an array of integers, find sum of array elements using recursion.
**Examples:
**Input: arr = [1, 2, 3]
**Output: 6
**Explanation: 1 + 2 + 3 = 6**Input: arr = [15, 12, 13, 10]
**Output: 50
**Explanation: 15 + 12 + 13 + 10 = 50
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.
recursive solution explanation
C++ `
#include <bits/stdc++.h> using namespace std;
int RecSum(vector &arr, int n) { if (n <= 0) return 0; return (RecSum(arr, n - 1) + arr[n - 1]); }
int arraysum(vector &arr){ return RecSum(arr,arr.size()); }
// Driver code int main() { vector arr = { 1, 2, 3, 4, 5 }; cout<<arraysum(arr); return 0; }
Java
class GfG { static int RecSum(int[] arr, int n) { if (n <= 0) return 0; return RecSum(arr, n - 1) + arr[n - 1]; }
static int arraysum(int[] arr) {
return RecSum(arr, arr.length);
}
public static void main(String[] args) {
int[] arr = {1, 2, 3, 4, 5};
System.out.println(arraysum(arr));
}
}
Python
Function to calculate the sum of an array recursively
def RecSum(arr, n): if n <= 0: return 0 return RecSum(arr, n - 1) + arr[n - 1]
def arraysum(arr): return RecSum(arr, len(arr))
Driver code
arr = [1, 2, 3, 4, 5] print(arraysum(arr))
C#
using System;
class GfG { static int RecSum(int[] arr, int n) { if (n <= 0) return 0; return RecSum(arr, n - 1) + arr[n - 1]; }
static int arraysum(int[] arr) {
return RecSum(arr, arr.Length);
}
public static void Main(string[] args) {
int[] arr = {1, 2, 3, 4, 5};
Console.WriteLine(arraysum(arr));
}
}
JavaScript
// Function to calculate the sum of an array recursively
function RecSum(arr, n) { if (n <= 0) return 0; return RecSum(arr, n - 1) + arr[n - 1]; }
function arraysum(arr) { return RecSum(arr, arr.length); }
// Driver code let arr = [1, 2, 3, 4, 5]; console.log(arraysum(arr));
`
**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.