85.2k views
1 vote
use the following recursive method. public int question(int x, int y) { if (x == y) return 0; else return question(x-1, y) 1; } if the method is called as question(8, 3), what is returned?

User Ben Bishop
by
7.9k points

1 Answer

2 votes
If the method is called as `question(8, 3)`, the method will return `5`.

Here's how the recursion works:

1. The initial call is `question(8, 3)`.
2. Since `x` and `y` are not equal, the method calls `question(x-1, y) + 1`, which is `question(7, 3) + 1`.
3. Since `7 != 3`, the method calls `question(6, 3) + 1`.
4. This continues until `question(3, 3)` is called, at which point the method returns `0`, since `3 == 3`.
5. Now each previous call can be evaluated: `question(4, 3)` returns `1`, `question(5, 3)` returns `2`, `question(6, 3)` returns `3`, `question(7, 3)` returns `4`, and finally `question(8, 3)` returns `5`.

So the final output of `question(8, 3)` is `5`.
User Izold Tytykalo
by
7.9k points