Sum of array elements using recursion
Last Updated :
19 Sep, 2023
Given an array of integers, find sum of array elements using recursion.
Examples:
Input : A[] = {1, 2, 3}
Output : 6
1 + 2 + 3 = 6
Input : A[] = {15, 12, 13, 10}
Output : 50
We have discussed iterative solution in below post.
Sum of elements in a given array
In this post, recursive solution is discussed.
C++
#include <stdio.h>
int findSum( int A[], int N)
{
if (N <= 0)
return 0;
return (findSum(A, N - 1) + A[N - 1]);
}
int main()
{
int A[] = { 1, 2, 3, 4, 5 };
int N = sizeof (A) / sizeof (A[0]);
printf ( "%d" , findSum(A, N));
return 0;
}
|
Java
public class Test {
static int arr[] = { 1 , 2 , 3 , 4 , 5 };
static int findSum( int A[], int N)
{
if (N <= 0 )
return 0 ;
return (findSum(A, N - 1 ) + A[N - 1 ]);
}
public static void main(String[] args)
{
System.out.println(findSum(arr, arr.length));
}
}
|
Python3
def _findSum(arr, N):
if N < = 0 :
return 0
else :
return _findSum(arr, N - 1 ) + arr[N - 1 ]
arr = []
arr = [ 1 , 2 , 3 , 4 , 5 ]
N = len (arr)
ans = _findSum(arr,N)
print (ans)
|
C#
using System;
class Test {
static int []arr = {1, 2, 3, 4, 5};
static int findSum( int []A, int N)
{
if (N <= 0)
return 0;
return (findSum(A, N - 1) + A[N - 1]);
}
public static void Main()
{
Console.Write(findSum(arr, arr.Length));
}
}
|
PHP
<?php
function findSum( $A , $N )
{
if ( $N <= 0)
return 0;
return (findSum( $A , $N - 1) +
$A [ $N - 1]);
}
$A = array (1, 2, 3, 4, 5);
$N = sizeof( $A );
echo findSum( $A , $N );
?>
|
Javascript
<script>
function findSum(A, N) {
if (N <= 0)
return 0;
return (findSum(A, N - 1) + A[N - 1]);
}
let A = [1, 2, 3, 4, 5];
let N = A.length;
document.write(findSum(A, N));
</script>
|
Time Complexity; O(n)
Here n is the number of elements in the array.
Auxiliary Space: O(n)
The extra space is used in recursion call stack.
How does above recursive solution work?
This article is contributed by
Prakhar Agrawal.
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...