1

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);
}
0

5 Answers 5

12

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
Sign up to request clarification or add additional context in comments.

1 Comment

I understand, blindingly obvious too. Thanks, I will accept in 10.
4

Just work through a simple example: Recursive(2)

invoke Recursive(2)
if(input <= 1) evaluates to false
so the else block is executed and the return value is 2 * Recursive(2 - 1)
invoke Recursive(1)
if(input <= 1) evaluates to true
so the return value of Recursive(2 - 1) is 1
thus the return value of Recursive(2) is 2 * 1 = 2

Let's work through another: Recursive(3)

invoke Recursive(3)
if(input <= 1) evalues to false
so the else block is executed adn the return value is 3 * Recursive(3 - 1)
but we just showed Recursive(2) evaluates to 2
so the return value of Recursive(3) is 3 * 2 = 6

1 Comment

Great breakdown of recursion +1
2

It doesn't. It returns 1, as expected, however, that return value is then passed back up the call stack and altered.

1 Comment

Not altered. Another value is returned.
2

It will return of the factorial of Input.

Recursion is a common techniques for solving many types of problems. According to the Wikipedia:

"Recursion in computer science is a method where the solution to a problem depends on solutions to smaller instances of the same problem. The approach can be applied to many types of problems, and is one of the central ideas of computer science".

Following Scheme code snippet will help you to understand how recursion works.

enter image description here

Comments

0

Set a watch for $ReturnValue1 and cycle through with debug to see the result multiplied.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.