0

I'm beginner in recursion and I did this code

#include <stdio.h>

int ft_recursive_factorial(int nb)
{
    if (nb > 1)
    {
        return(nb * ft_recursive_factorial(nb - 1));
    }
    return(1);
}

int main()
{
    printf("%d\n",ft_recursive_factorial(3));
    return(0);
}


Output

6

I think the code is correct but i can't understand what happen in the stack... In my mind this happening:

| Stack |
| return(1 * ft_recursive_factorial(1 - 1)) |
| return(2 * ft_recursive_factorial(2 - 1)) |
| return(3 * ft_recursive_factorial(3 - 1)) |
In this schema the code would be stop at return(1 * ft_recursive_factorial(1 - 1)) because of the return answer (in my mind).

Can someone explain me what happening in the stack ? please.

Myno
  • 158
  • 2
  • 13
  • Does this answer your question? [How exactly does the callstack work?](https://stackoverflow.com/questions/23981391/how-exactly-does-the-callstack-work) – Paul Hankin May 07 '20 at 07:49
  • 1
    No. In the schema, the code would stop at `return(1)` since it does not match the previous condition. – samthegolden May 07 '20 at 08:25

1 Answers1

1

To really spell it out, it'll go like this:

In main(), calling ft_recursive_factorial(3)
  In ft_recursive_factorial(nb == 3)
  nb > 1 is true, so
  Calling ft_recursive_factorial(2) from ft_recursive_factorial(3) 
    In ft_recursive_factorial(nb == 2)
    nb > 1 is true, so
    Calling ft_recursive_factorial(1) from ft_recursive_factorial(2) 
      In ft_recursive_factorial(nb == 1)
      nb > 1 is false, so 
      return 1
    back in ft_recursive_factorial(2), receiving result 1 from recursive call
    return nb(2) * recursive result(1) i.e. 2 to caller
  back in ft_recursive_factorial(3), receiving result 2 from recursive call
  return nb(3) * recursive result(2) i.e. 6 to caller
back in main(), receiving result 6.