jozencl - 1 year ago 30

Java Question

`public static void main(String[]args){`

multiply(2,4);

}

public static int multiply(int a, int b) {

if (b == 0) {

return 0;

}

return a + multiply(a, b - 1);

}

}

I have this recursive statement, and I am wondering how it works, is this the correct way to think about it?

`return 2 + (2, 3);`

return 2 + (2,2);

return 2 + (2,1);

return 2 + (2,0);

return 2 + 6;

return 2 + 4;

return 2 + 2;

return 2 + 0;

Answer

I'm not exactly clear on what you are showing, though it looks fairly correct (if I'm interpreting it correctly). You need to work through each call of the method until you hit the base case (in this instance, it is when `b == 0`

). Then, you can work your way back up, substituting in the values that are returned.

`multiply(2,4)`

returns `2 + multiply(2,3)`

.
`multiply(2,3)`

returns `2 + multiply(2,2)`

.
`multiply(2,2)`

returns `2 + multiply(2,1)`

.
`multiply(2,1)`

returns `2 + multiply(2,0)`

.
`multiply(2,0)`

returns `0`

.

So, if we substitute in the return values, working from the bottom up, you get:

`return 2 + 2 + 2 + 2 + 0;`

which equals `8`

. `2 x 4 = 8`

.

Source (Stackoverflow)