Br.sasa - 7 months ago 81

Java Question

I'm really confused in this program:

`public static int product(int n1, int n2) {`

if (n2== 0 || n1==0) {

return 0;

}

n1 += product(n1, n2 - 1);

return n1;

}

Suppose i made product(3,2), then must function returns:

Sence 3>0 and 2>0 then n1= 3+ product(3,1)

Sence 3>0 and 1>0 then n1= 3+ 3+ product(3,1)

3>0 but 0==0 then return 0;

but it returns 6.

Can some one explain that ?

Answer

You are correct in your explanation of how the method works, but remember, since this is recursive, it ends up returning the total of all returns. Let me explain: The first recursion returns 3 + product(3, 1). However, your program does not know what product(3, 1) is yet, so it must continue before returning. The second recursion (product(3, 1)) returns 3 + product(3, 0). Again, your program must continue the recursion to find product(3, 0). The third and final recursion returns 0, as you said, but the FINAL answer goes back to the first recursion's answer, 3 + product(3, 1). We know that product(3, 1) = 3 + product(3, 0), and product(3, 0) = 0. So product(3, 2) = 3 + 3 + 0, which is 6. It appears in your answer that you were expecting only to receive the final recursion for an answer, but because of your return statement, it is a combination of the three.