At the risk of sounding stupid, why does the following method return the result instead of the value 1 when the conditional block equates to true?
public long Recursive(int Input)
{
if (Input <= 1)
return 1;
else
return Input * Recursive(Input - 1);
}
It does return 1 at the point that Input == 1
.
But the 1 returned is used with the prior call, multiplied by Input
, the return value of which is used with the prior call, multiplied by Input
, the return value of which is used with the prior call, multiplied by Input
, the return value of which is used with the prior call, multiplied by Input
... until you have gotten back to the first call to Recursive
.
Try to see what happens when you call Recursive
with the value 3
:
- input is not 1, so it calls Recursive with the value 2 - input is not 1, so it calls Recursive with the value 1 - input is 1, 1 is returned - 2 * 1 is returned - 3 * 2 is returned