How to find sum of array elements using recursion.
Given an array of integers. Write a code to find sum of array using recursion.
For example :
Input: arr[] = {2, 5, 6, 8, 9, 12}
Output : 42 (2+5+6+8+9+12)
In this problem, we have given an array of length n, we need to find and return the sum of all elements of the array. We have to do it recursively.
In this tutorial, I am going to explain the approach and it’s java code to calculate the sum of array elements using recursion.
Before solving this problem recursively. Let’s discuss how we can calculate the sum of array elements using an iterative approach.
Here are the following steps to calculate the sum of array elements using an iterative approach.
i) We first traverse an array by using a loop.
ii) For this let’s declare a variable sum, which stores the sum of array elements. Add each array element to a sum variable. After the complete traversal of an array return or print the value of a sum variable.
Here is the java code for the iterative approach.
1 2 3 4 5 6 7 8 9 10 11 12 13 |
//Iterative approach to calculate sum private int calculateSum(int[] arr) { int sum = 0; //Add each array element to sum variable for(int i = 0; i < arr.length; i++) { sum = sum + arr[i]; } //return final result return sum; } |
Programming questions on arrays
If you want to understand what’s the difference between iterative and recursive approaches then check my previous tutorial on Recursion vs Iteration.
Find Sum of Array Elements using Recursion – Java Code
The calculating sum of array elements using an iterative approach is simple and straightforward. Let’s discuss how to calculate the sum of array elements using recursion.
To solve this problem recursively, I have created one method calculateSum(). It takes two arguments one is an array and the second is the length of an array. The method calculateSum() calls itself recursively until the base or terminating condition is not reached.
The base condition is when the value of n is less than or equal to zero. Until the value of n is not reached zero it calls itself.
find sum of digits of a number using recursion
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 |
/* * Find Sum of Array Elements - Java Code */ public class SumOfArrayElements { private static int calculateSum(int arr[], int n) { //base or terminating condition if (n <= 0) { return 0; } //Calling method recursively return calculateSum(arr, n-1 ) + arr[n-1]; } public static void main(String[] args) { int arr[] = {2, 5, 6, 8, 9, 12}; int sum = calculateSum(arr, arr.length); System.out.println(sum); } } |
Calculate the Sum of Array Elements using Recursion – Video Tutorial
For a detailed explanation, I have added the video tutorial. In this tutorial, I have explained the recursive approach to calculating the sum of array elements.