Find Sum of Array Elements using Recursion – Java Code

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.

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.

Programming video tutorials

Here is the java code for the iterative approach.

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

Sum of Array Elements using Recursion

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.

Sum of array elements using recursion video tutorial

Tagged , , . Bookmark the permalink.

About WebRewrite

I am technology lover who loves to keep updated with latest technology. My interest field is Web Development.