Hi all,
I'm very, very bad at recursion. I have a problem in which I need to use a recursive method to calculate the product of all the elements in an array (e.g. an array with 1, 2, 3, 4 would return 24).
I've tried writing a method, but I keep getting a stack overflow area. The problem says to use a marker to keep track of the position in the array.
I can multiply the elements easy enough using an array and a for loop, but using recursion is very difficult for me, as I'm very new to it.
Here's what I have so far:
public int productRecursion(int[] numbers, int marker) {
int result = numbers[0];
for (int i = marker; i < numbers.length; i++) {
result = result * numbers;
}
if (marker > numbers.length) {
return result;
} else {
return productRecursion(numbers, marker++);
}
}
It just gives a stack overflow error as soon as I run the program. I'd love to start debugging the method, but it was very hard for me to even write it, and I'm not sure where to start.
Recursion is very, very confusing to me, so I think I need to understand more than I could gain from a simple debugging.
Can anyone offer some advice?
Thanks