# Recursion

Most of us know what recursion is and can write recursive code if we are asked to. But when we try to solve advance problems(i.e binary tree, binary search tree etc.) and see recursive solutions, we get confused about how that code is working, so in this post, I will try to explain how a recursive code works behind the scene with a simple factorial finding recursive code, and we will be able to trace more complex recursive code the same way.

Now let’s see the c++ code to return the factorial of a number :

**How does this code work?**

At first main() function calls the factorial(5), so in the stack at first main() is added and after that at the top of the stack factorial(5) is added.

In the function initially n = 5 then on line 5 it checks if n = 0, as it is not program goes to line 8 and return 5 * factorial(4). So, factorial(4) is added to the stack. Here, 5 * factorial(4) is called from factorial(5), which means whenever…