Reputation:
Here is my code:
public int sum(int[] array, int index)
{
//int index is the number of elements in the array.
//Here is my base case:
if (index == 0)
return 0;
//Now it's time for the recursion
else
return array[index] + sum(array, index + 1);
}
I keep on getting an out of bounds error, but I don't what I am doing wrong.
Upvotes: 0
Views: 18776
Reputation: 1932
If you are using Java 1.8 you can do the following
public int sum(int[] array)
{
return (int)array.stream().sum();
}
or even
public int sum(int[] array)
{
return (int)array.sum();
}
Upvotes: 0
Reputation: 3609
instead of going from 0 to highest index , go from highest index to 0, i did (index -1) because you said index is total elements, so if array has 10 elements, last element has index 9
public int sum(int[] array, int index)
{
//int index is the number of elements in the array.
//Here is my base case:
if (index == 0)
return 0;
//Now it's time for the recursion
else
return array[index-1] + sum(array, (index - 1);
}
Upvotes: 1
Reputation: 1
@ Masud - you're code has a logical error though (i'm beginner Java so sorry if i'm incorrect).
return array[index] + sum(array, index - 1);
array[index]
will receive a out-of-bounds error as index starts at 0 - hence meaning there won't be an index there. 'index - 1' would work. Also, this would change your base case to return '0' as returning array[0] will have array[0] added twice and an incorrect sum.
This is my code:
public static int sumArrayRecursion(int array[], int n){
if (n == 0){
return 0;
}
else {
return array[n-1] + sumArrayRecursion(array, n-1);
}
}
Upvotes: 0
Reputation: 213243
Your base condition is faulty. It should be:
if (index == array.length)
Note, you need to pass index = 0
on first call. If you are passing index = array.length - 1
, then keep the base case as it is, and change the recursive method invocation to pass index - 1
, instead of index + 1
.
However, do you really need recursion? I would seriously give it hundreds of thoughts before reaching out for recursion instead of loop for this task.
Upvotes: 8
Reputation: 21961
Try,
public static void main(String[] args){
int arr[] = {3, 4, 6, 7};
System.out.println(sum(arr, arr.length-1));
}
public static int sum(int[] array, int index) {
if (index == 0) {
return array[0];
} else {
return array[index] + sum(array, index - 1);
}
}
Upvotes: 2