Linear Sum using Recursion in Java

Linear Sum, sum of the “n” array elements can be computed easily by looping through the elements, this can be solved using recursion also. Devise last array element every time and solve the similar problem for remaining “n-1” array elements, will devising add intermediate result . Algorithm or Recurrence relation for the Linear Sum problem can be as follows.

Algorithm or Recurrence relation

linearSum(a,n)

if n=1 then                     //base case
return a[0];
else                                //recursive case
return linearSum(a[n-1])+a[n-1];

Linear Sum using Recursion implementation in Java

Here is the implementation of linear sum using recursion in java

package com.jminded.recursion;

public class LinearSumUsingRecursion {

	/**
	 * @author Umashankar
	 * {@link https://jminded.com}
	 * @param args
	 */
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		//define an array 
		int[] arr={0,1,2,3,4,5,6};
		int length=arr.length;
		System.out.println(linearSum(arr,length));

	}
	/**
	 * <p>Linear Sum</p>
	 *  if n=1 then  //base case
	 *     return a[0];
	 *  else         //recursive case  
	 *     return linearSum(a[n-1])+a[n-1];   
	 * @param a
	 * @param n
	 * @return
	 */
	public static int linearSum(int[] a,int n){
		//n--array length
		//base case
		if(n==1){
			return a[0];
		}
		//recursive case
		else if(n>0){
			return linearSum(a,n-1)+a[n-1];
		}else{
			return -1;
		}
	}
}

 Output

21

Leave a Comment