Mark As Completed Discussion

Working of Factorial: Iterative vs. Recursive Case

Look at the diagrams below to see the "behind the scenes" portion of the activation stack for both the iterative and recursive cases:

Working Of Factorial Iterative Vs. Recursive Case

The most important thing to note is that the iterative version has only one function record on the activation stack. For the recursive cases, there are 4 records of the function on the activation stack until the recursion starts to unwind.

So imagine what would happen if you were to call factorial for a larger number like 10 or 20. So many records on the activation stack is a strain on the system's memory! There is also the extra overhead of function calling, saving its state, and maintaining the activation stack.

If you are using a programming language like C++ or Java, then go for the iterative solution as it would run in constant memory.