29.5k views
1 vote
public static int recur(int x) { if (x >= 0) return x + recur(x - 1); return 0; } What is returned by the method call recur(9)?

User Stewsha
by
5.8k points

1 Answer

6 votes
9 >= 0 so return 9 + ...
8 >= 0 so return 8 + ...
7 >= 0 so return 7 + ...
6 >= 0 so return 6 + ...
5 >= 0 so return 5 + ...
4 >= 0 so return 4 + ...
3 >= 0 so return 3 + ...
2 >= 0 so return 2 + ...
1 >= 0 so return 1 + ...
0 >= 0 so return 0 + ...
-1 is not >= 0 so return 0.

Now string together all the returns..
9+8+7+6+5+4+3+2+1+0+0=45

recur(9) returns 45
User Alex Moreno
by
5.7k points