For the past couple of hours, I have tried to understand why the output for this program is behaving in such a weird manner. The first part of the recursive functions makes sense to me, however, the rest I, unfortunately, find extremely confusing.
I was wondering how come that the program is going backward, and even adds to a variable that should be subtracted instead. This does not make any sense to me. I would appreciate any help, thanks.
Here is my recursive function:
public static void threeWays(int id, int n) {
if (n >= 0) {
System.out.println(id + "=" + n);
threeWays(id + 1, n - 1);
threeWays(id + 1, n - 2);
threeWays(id + 1, n - 3);
}
}
public static void main(String[] args) {
threeWays(1, 4);
}
And here's the output:
1=4
2=3
3=2
4=1
5=0
4=0
3=1
4=0
3=0
2=2
3=1
4=0
3=0
2=1
3=0