Skip to Main Content

Java Programming

Announcement

For appeals, questions and feedback about Oracle Forums, please email oracle-forums-moderators_us@oracle.com. Technical questions should be asked in the appropriate category. Thank you!

Recursive method to calculate product of elements in an array

800306Aug 14 2007 — edited Aug 15 2007
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
Comments
Locked Post
New comments cannot be posted to this locked post.
Post Details
Locked on Sep 12 2007
Added on Aug 14 2007
7 comments
2,471 views