Recursion in c++ Factorial Program

后端 未结 5 1216
渐次进展
渐次进展 2020-12-05 16:48

hello i have this piece of code that i coded based on some other recursion and factorial programs but my problem is that i am really confused as to how it stored the value a

5条回答
  •  旧时难觅i
    2020-12-05 17:42

    Return 1 is not returning the actual answer. It's just returning the answer to calling

    factorialfinder(1);
    

    which happens in your code.

    In any program, a call stack is a space in memory that is used to keep track of function calls. Space from this memory is used to store the arguments to a function, as well as the return value of that function. Whenever some function A calls another function B, A gets the return value of B from that space.

    A recursive function is nothing special, it's just an ordinary function calling another function (that happens to be itself). So really, when a recursive function F calls itself, it's calling another function: F calls F', which calls F'', which calls F''', etc. It's just that F, F'', F''' etc. execute the same code, just with different inputs.

    The expression if (x == 1) is there to check when this process should be stopped. The return value of F''' is used by F''. The return value of F'' is used by F'. The return value of F' is used by F.

    In Factorial of some number, the operation is (n) * (n-1) * (n-2) * .... * (1). I've highlighted the 1; this is the condition that's being checked.

提交回复
热议问题