The Wayback Machine - https://web.archive.org/web/20240921070340/https://www.geeksforgeeks.org/sum-array-elements-using-recursion/
Open In App

Sum of array elements using recursion

Last Updated : 19 Sep, 2023
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow
Show Topics
Solve Problem
Basic
74.98%
1.1L

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
Recommended Problem

We have discussed iterative solution in below post. 
Sum of elements in a given array

In this post, recursive solution is discussed. 

C++




// C++ program to find sum of array
// elements using recursion.
#include <stdio.h>
  
// Return sum of elements in A[0..N-1]
// using recursion.
int findSum(int A[], int N)
{
    if (N <= 0)
        return 0;
    return (findSum(A, N - 1) + A[N - 1]);
}
  
// Driver code
int main()
{
    int A[] = { 1, 2, 3, 4, 5 };
    int N = sizeof(A) / sizeof(A[0]);
    printf("%d", findSum(A, N));
    return 0;
}


Java




// Java program to find sum of array
// elements using recursion.
  
public class Test {
    static int arr[] = { 1, 2, 3, 4, 5 };
  
    // Return sum of elements in A[0..N-1]
    // using recursion.
    static int findSum(int A[], int N)
    {
        if (N <= 0)
            return 0;
        return (findSum(A, N - 1) + A[N - 1]);
    }
  
    // Driver method
    public static void main(String[] args)
    {
        System.out.println(findSum(arr, arr.length));
    }
}


Python3




# Python program to find sum of array
# elements using recursion.
  
 # Return sum of elements in A[0..N-1]
 # using recursion.
def _findSum(arr, N):
    if N <= 0:
        return 0
    else:
        return _findSum(arr, N - 1) + arr[N - 1]
  
# driver code
arr =[]
# input values to list
arr = [1, 2, 3, 4, 5]
   
# calculating length of array
N = len(arr)
   
ans =_findSum(arr,N)
print (ans)
   
# This code is contributed by Khare Ishita


C#




// C# program to find sum of array
// elements using recursion.
using System;
  
class Test {
      
    static int []arr = {1, 2, 3, 4, 5};
  
    // Return sum of elements in 
    // A[0..N-1] using recursion.
    static int findSum(int []A, int N)
    {
        if (N <= 0)
            return 0;
        return (findSum(A, N - 1) + A[N - 1]);
    }
  
    // Driver Code
    public static void Main()
    {
        Console.Write(findSum(arr, arr.Length));
    }
}
  
// This code is contributed by Nitin Mittal.


PHP




<?php
// PHP program to find sum 
// of array elements using
// recursion.
  
// Return sum of elements 
// in A[0..N-1] using recursion.
function findSum($A, $N)
{
    if ($N <= 0)
        return 0;
    return (findSum($A, $N - 1) + 
                    $A[$N - 1]);
}
  
// Driver code
$A = array(1, 2, 3, 4, 5);
$N = sizeof($A);
echo findSum($A, $N);
      
// This code is contributed 
// by ihritik
?>


Javascript




<script>
  
// JavaScript program to find sum of array
// elements using recursion.
  
// Return sum of elements in A[0..N-1]
// using recursion.
function findSum(A, N) {
    if (N <= 0)
        return 0;
    return (findSum(A, N - 1) + A[N - 1]);
}
  
// Driver code
  
let A = [1, 2, 3, 4, 5];
let N = A.length;
document.write(findSum(A, N));
  
</script>


Output

15

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.



Previous Article
Next Article

Similar Reads

Why is Tail Recursion optimization faster than normal Recursion?
What is tail recursion? Tail recursion is defined as a recursive function in which the recursive call is the last statement that is executed by the function. So basically nothing is left to execute after the recursion call. What is non-tail recursion? Non-tail or head recursion is defined as a recursive function in which the recursive call is the f
4 min read
Sum of even elements of an Array using Recursion
Given an array arr[] of integers, the task is to find the sum of even elements from the array. Examples: Input: arr[] = {1, 2, 3, 4, 5, 6, 7, 8} Output: 20 2 + 4 + 6 + 8 = 20Input: arr[] = {4, 1, 3, 6} Output: 10 4 + 6 = 10 Approach: Write a recursive function that takes the array as an argument with the sum variable to store the sum and the index
5 min read
Tail recursion to calculate sum of array elements.
Given an array A[], we need to find the sum of its elements using Tail Recursion Method. We generally want to achieve tail recursion (a recursive function where recursive call is the last thing that function does) so that compilers can optimize the code. Basically, if recursive call is the last statement, the compiler does not need to save the stat
3 min read
Sum of array elements possible by appending arr[i] / K to the end of the array K times for array elements divisible by K
Given an array arr[] consisting of N integers and an integer K, the task is to find the sum of the array elements possible by traversing the array and adding arr[i] / K, K number of times at the end of the array, if arr[i] is divisible by K. Otherwise, stop the traversal. Examples: Input: arr[] = {4, 6, 8, 2}, K = 2Output: 44Explanation:The followi
14 min read
Sum of natural numbers using recursion
Given a number n, find sum of first n natural numbers. To calculate the sum, we will use a recursive function recur_sum().Examples : Input : 3 Output : 6 Explanation : 1 + 2 + 3 = 6 Input : 5 Output : 15 Explanation : 1 + 2 + 3 + 4 + 5 = 15 Below is code to find the sum of natural numbers up to n using recursion : C/C++ Code // C++ program to find
3 min read
Sum of the series 1^1 + 2^2 + 3^3 + ..... + n^n using recursion
Given an integer n, the task is to find the sum of the series 11 + 22 + 33 + ..... + nn using recursion. Examples: Input: n = 2 Output: 5 11 + 22 = 1 + 4 = 5 Input: n = 3 Output: 32 11 + 22 + 33 = 1 + 4 + 27 = 32 Approach: Starting from n, start adding all the terms of the series one by one with the value of n getting decremented by 1 in each recur
3 min read
Find Maximum Level Sum in Binary Tree using Recursion
Given a Binary Tree having positive and negative nodes, the task is to find the maximum sum level in it and print the maximum sum.Examples: Input: 4 / \ 2 -5 / \ / \ -1 3 -2 6 Output: 6 Sum of all nodes of the 1st level is 4. Sum of all nodes of the 2nd level is -3. Sum of all nodes of the 3rd level is 6. Hence, the maximum sum is 6. Input: 1 / \ 2
10 min read
Count of subsets with sum equal to X using Recursion
Given an array arr[] of length N and an integer X, the task is to find the number of subsets with a sum equal to X using recursion.Examples: Input: arr[] = {2, 3, 5, 6, 8, 10}, X = 10 Output: 3 Explanation: All possible subsets with sum 10 are {2, 3, 5}, {2, 8}, {10} Input: arr[] = {1, 2, 3, 4, 5}, X = 7 Output: 3 Explanation: All possible subsets
8 min read
Find geometric sum of the series using recursion
Given an integer N, we need to find the geometric sum of the following series using recursion. 1 + 1/3 + 1/9 + 1/27 + ... + 1/(3^n) Examples: Input N = 5 Output: 1.49794 Input: N = 7 Output: 1.49977 Approach:In the above-mentioned problem, we are asked to use recursion. We will calculate the last term and call recursion on the remaining n-1 terms e
3 min read
Sum of N-terms of geometric progression for larger values of N | Set 2 (Using recursion)
A Geometric series is a series with a constant ratio between successive terms. The first term of the series is denoted by a and the common ratio is denoted by r. The series looks like this:- [Tex]a, ar, ar^2, ar^3, ar^4,... [/Tex]The task is to find the sum of such a series, mod M. Examples: Input: a = 1, r = 2, N = 10000, M = 10000 Output: 8751 In
7 min read
Sum of digit of a number using recursion
Given a number, we need to find sum of its digits using recursion.Examples:   Input : 12345Output : 15Input : 45632Output :20   The step-by-step process for a better understanding of how the algorithm works. Let the number be 12345. Step 1-&gt; 12345 % 10 which is equal-too 5 + ( send 12345/10 to next step ) Step 2-&gt; 1234 % 10 which is equal-too
4 min read
Program to check if an array is palindrome or not using Recursion
Given an array. The task is to determine whether an array is a palindrome or not using recursion. Examples: Input: arr[] = {3, 6, 0, 6, 3}Output: Palindrome Input: arr[] = {1, 2, 3, 4, 5}Output: Not Palindrome Approach: Base case: If array has only one element i.e. begin == end then return 1, also if begin&gt;end which means the array is palindrome
4 min read
Mean of array using recursion
To find the mean of the elements of the array. Mean = (Sum of elements of the Array) / (Total no of elements in Array) Examples: Input : 1 2 3 4 5 Output : 3 Input : 1 2 3 Output : 2 To find the mean using recursion assume that the problem is already solved for N-1 ie you have to find for n Sum of first N-1 elements = (Mean of N-1 elements)*(N-1) M
4 min read
Construct an Array of size N in which sum of odd elements is equal to sum of even elements
Given an integer N which is always even, the task is to create an array of size N which contains N/2 even numbers and N/2 odd numbers. All the elements of array should be distinct and the sum of even numbers is equal to the sum of odd numbers. If no such array exists then print -1.Examples: Input: N = 8 Output: 2 4 6 8 1 3 5 11 Explanation: The arr
7 min read
Find the Array Permutation having sum of elements at odd indices greater than sum of elements at even indices
Given an array arr[] consisting of N integers, the task is to find the permutation of array elements such that the sum of odd indices elements is greater than or equal to the sum of even indices elements. Examples: Input: arr[] = {1, 2, 3, 4}Output: 1 4 2 3 Explanation:Consider the permutation of the given array as {1, 4, 2, 3}.Now, the sum of elem
6 min read
For all Array elements find Product of Sum of all smaller and Sum of all greater elements
Given an array arr[] of integers of length N, the task is to find the product of the sum of all the numbers larger than that number with the sum of all the numbers less than that number for each number in the array. Examples: Input: arr[] = {8, 4, 9, 3}, N = 4Output:- 63, 51, 0, 0Explanation:For first number 8: Sum of elements smaller than this is
15 min read
Modify array to another given array by replacing array elements with the sum of the array
Given an array input[] consisting only of 1s initially and an array target[] of size N, the task is to check if the array input[] can be converted to target[] by replacing input[i] with the sum of array elements in each step. If found to be true, then print "YES". Otherwise, print "NO". Examples: Input: input[] = { 1, 1, 1 }, target[] = { 9, 3, 5 }
13 min read
Modify array to another given array by replacing array elements with the sum of the array | Set-2
Given an Array input[] consisting only of 1s initially and an array target[] of size N, the task is to check if the array input[] can be converted to target[] by replacing input[i] with the sum of array elements in each step. Examples: Input: input[] = { 1, 1, 1 }, target[] = { 9, 3, 5 } Output: YES Explanation: Replacing input[1] with (input[0] +
10 min read
Decimal to Binary using recursion and without using power operator
Given an integer N, the task is convert and print the binary equaiva;ent of N.Examples: Input: N = 13 Output: 1101Input: N = 15 Output: 1111 Approach Write a recursive function that takes an argument N and recursively calls itself with the value N / 2 as the new argument and prints N % 2 after the call. The base condition will be when N = 0, simply
3 min read
Sum of elements in 1st array such that number of elements less than or equal to them in 2nd array is maximum
Given two unsorted arrays arr1[] and arr2[], the task is to find the sum of elements of arr1[] such that the number of elements less than or equal to them in arr2[] is maximum. Examples: Input: arr1[] = {1, 2, 3, 4, 7, 9}, arr2[] = {0, 1, 2, 1, 1, 4} Output: 20 Below table shows the count of elements in arr2[] which are ? the elements of arr1[] arr
15 min read
Count array elements that can be represented as sum of at least two consecutive array elements
Given an array A[] consisting of N integers from a range [1, N], the task is to calculate the count of array elements (non-distinct) that can be represented as the sum of two or more consecutive array elements. Examples: Input: a[] = {3, 1, 4, 1, 5, 9, 2, 6, 5}Output: 5Explanation:The array elements satisfying the condition are: 4 = 3 + 1 5 = 1 + 4
11 min read
Maximize sum of odd-indexed array elements by repeatedly selecting at most 2*M array elements from the beginning
Given an array arr[] consisting of N integers and an integer M (initially 1), the task is to find the maximum sum of array elements chosen by Player A when two players A and B plays the game optimally according to the following rules: Player A starts the game.At every chance, X number of elements can be chosen from the beginning of the array, where
15+ min read
Minimum sum of values subtracted from array elements to make all array elements equal
Given an array arr[] consisting of N positive integers, the task is to find the sum of all the array elements required to be subtracted from each array element such that remaining array elements are all equal. Examples: Input: arr[] = {1, 2}Output: 1Explanation: Subtracting 1 from arr[1] modifies arr[] to {1, 1}. Therefore, the required sum is 1. I
4 min read
Make all array elements even by replacing any pair of array elements with their sum
Given an array arr[] consisting of N positive integers, the task is to make all array elements even by replacing any pair of array elements with their sum. Examples: Input: arr[] = {5, 6, 3, 7, 20}Output: 3Explanation: Operation 1: Replace arr[0] and arr[2] by their sum ( = 5 + 3 = 8) modifies arr[] to {8, 6, 8, 7, 20}.Operation 2: Replace arr[2] a
5 min read
Make all array elements even by replacing adjacent pair of array elements with their sum
Given an array arr[] of size N, the task is to make all array elements even by replacing a pair of adjacent elements with their sum. Examples: Input: arr[] = { 2, 4, 5, 11, 6 }Output: 1Explanation:Replacing a pair (arr[2], arr[3]) with their sum ( = 5 + 11 = 16) modifies arr[] to { 2, 4, 16, 16, 6 } Since all array elements are even, the required o
8 min read
Check if all array elements can be made divisible by K by replacing array elements with sum of pairs
Given an array arr[] of size N and a positive integer K, the task is to make every element of the array divisible by K by repeatedly selecting a pair of indices (i, j) and perform arr[i] = arr[i] + arr[j]. Examples: Input: arr[] = {3, 6, 3}, K = 6Output: TrueExplanation: Update arr[0] = arr[0] + arr[0].Update arr[2] = arr[2] + arr[2] Input: arr[] =
7 min read
Sum of Bitwise XOR of elements of an array with all elements of another array
Given an array arr[] of size N and an array Q[], the task is to calculate the sum of Bitwise XOR of all elements of the array arr[] with each element of the array q[]. Examples: Input: arr[ ] = {5, 2, 3}, Q[ ] = {3, 8, 7}Output: 7 34 11Explanation:For Q[0] ( = 3): Sum = 5 ^ 3 + 2 ^ 3 + 3 ^ 3 = 7.For Q[1] ( = 8): Sum = 5 ^ 8 + 2 ^ 8 + 3 ^ 8 = 34.For
9 min read
Generate an N-length array with sum equal to twice the sum of its absolute difference with same-indexed elements of given array
Given an array arr[] of size N, the task is to construct an array brr[] of size N that satisfies the following conditions: In every pair of consecutive elements in the array brr[], one element must be divisible by the other, i.e. brr[i] must be divisible by brr[i + 1] or vice-versa.Every ith element in the array brr[] must satisfy brr[i] &gt;= arr[
5 min read
Difference between ceil of array sum divided by K and sum of ceil of array elements divided by K
Given an array arr[] and an integer K, the task is to find the absolute difference between the ceil of the total sum of the array divided by K and the sum of the ceil of every array element divided by K. Examples: Input: arr[] = {1, 2, 3, 4, 5, 6}, K = 4Output: 2Explanation: Sum of the array = 21. Ceil of ( Sum of the array ) / K = 6.Sum of ceil of
6 min read
Check if there exist two elements in an array whose sum is equal to the sum of rest of the array
We have an array of integers and we have to find two such elements in the array such that sum of these two elements is equal to the sum of rest of elements in array. Examples: Input : arr[] = {2, 11, 5, 1, 4, 7} Output : Elements are 4 and 11 Note that 4 + 11 = 2 + 5 + 1 + 7 Input : arr[] = {2, 4, 2, 1, 11, 15} Output : Elements do not exist A simp
15+ min read
Practice Tags :