Can someone please explain how this method works?
I tried adding System.out.print
statements but it didn't get me anywhere and
I simply cannot seem to get my head around it at the moment.
public static double recursive(double x, double y, int n) {
if(n==0) {
return x;
}
return recursive(x, y, n-1) * (1+y);
}
EDIT: I have realised that I looked at this method from the wrong perspective (not sure how this happened but it did) and in a moment of panic I decided to ask for the wisdom of the masses.
The explanations for this are very clear and concise, also in regard to recursion in general, which is why I'd like to keep the post up rather than delete my moment of tomfoolery.
The method multiplies x
by 1 + y
an n
number of times. In other words, the method will return x*(1+y)^n
in the end. This is given that the original n > 0
. If n
is originally less than 0, the method will recurse infinitely.
Explanation: When the method "enters" recursion and calls itself, it will do so n
number of times since we decrease n
by 1 until n
equals 0. When n
finally reaches 0, the innermost call of recursion will return x
. Each consecutive call will multiply the output of the previous call by 1+y
.