Welcome to the Java Programming Forums

The professional, friendly Java community. 21,500 members and growing!

The Java Programming Forums are a community of Java programmers from all around the World. Our members have a wide range of skills and they all have one thing in common: A passion to learn and code Java. We invite beginner Java programmers right through to Java professionals to post here and share your knowledge. Become a part of the community, help others, expand your knowledge of Java and enjoy talking with like minded people. Registration is quick and best of all free. We look forward to meeting you.

>> REGISTER NOW TO START POSTING

# Thread: Divide and conquer Algorithm

1. ## Divide and conquer Algorithm

I am learning divide and conquer algorithms in school and I am having some trouble figuring it out. I am required to find the sum of an array but divide and conquering an array to base case 4 then finding the sum of those 4 numbers. I think I have the basic idea of divide and conquer, but I cannot get my code below to work.

I keep getting this error
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 8
at getSum.sumArray(getSum.java:17)
at getSum.sumArray(getSum.java:21)
at getSum.main(getSum.java:7)

```public class getSum {
static int sum = 0;
public static void main(String[] args) {
int[] numbers = {2,2,2,2,2,2,2,2};
int amount = 0;
amount = sumArray(0,numbers.length,numbers);
System.out.print(amount);
}

public static int sumArray(int first, int last, int[] A){
int index = last - first;
if(index == 1){
return sum;
}else if(index <= 4 && index > 1){
for(int i = first; first < last; i++){
sum += A[i];
}
return sum;
}
return (sumArray(first, last / 2, A) + sumArray(last / 2, A.length, A));
}
}```

2. ## Re: Divide and conquer Algorithm

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 8
at getSum.sumArray(getSum.java:17)
The code at line 17 uses an index that is past the end of the array.
Remember that array indexes range from 0 to the array length-1

If you can't see how the variable's value gets its value, add some println calls to print out the values of the variables so you can see what the computer see.