Factorial using Recursion in Java

前端 未结 18 1453
春和景丽
春和景丽 2020-11-27 13:43

I am learning Java using the book Java: The Complete Reference. Currently I am working on the topic Recursion.

Please Note: There are similar questi

18条回答
  •  醉话见心
    2020-11-27 13:52

    IMHO, the key for understanding recursion-related actions is:

    1. First, we dive into stack recursively, and with every call we somehow modify a value (e.g. n-1 in func(n-1);) which determines whether the recursion should go deeper and deeper.
    2. Once recursionStopCondition is met (e.g. n == 0), the recursions stops, and methods do actual work and return values to the caller method in upper stacks, thus bubbling to the top of the stack.
    3. It is important to catch the value returned from deeper stack, somehow modify it (multiplying by n in your case), and then return this modified value topwards the stack. The common mistake is that the value from the deepest stack frame is returned straight to the top of the stack, so that all method invocations are ignored.

    Surely, methods can do useful work before they dive into recursion (from the top to the bottom of the stack), or on the way back.

提交回复
热议问题