Myno
Myno

Reputation: 158

Recursion C: What happen in the Stack?

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.

Upvotes: 0

Views: 336

Answers (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.

Upvotes: 1

Related Questions