Sunday, 23 August 2015

Recursion to find sum of elements in array

Write a recursive function that computes and returns the sum of all elements in an array.
import java.util.Objects;

public class SumOfElements {

 public static int getSum(int arr[]) {
  Objects.nonNull(arr);
  return sum(arr, arr.length - 1);

 }

 private static int sum(int arr[], int index) {
  if (index == 0)
   return arr[index];

  return arr[index] + sum(arr, index - 1);
 }
}


Following is the junit test case for above program.
import static org.junit.Assert.*;

import org.junit.Test;

public class SumOfElementsTest {

 @Test
 public void test1() {
  int arr1[] = { 1, 2, 3, 4 };
  int arr2[] = { 1 };
  int arr3[] = { 5, 6, 7, 8 };
  
  assertEquals(SumOfElements.getSum(arr1), 10);
  assertEquals(SumOfElements.getSum(arr2), 1);
  assertEquals(SumOfElements.getSum(arr3), 26);
 }
}


No comments:

Post a Comment