computing factorial using recursion

In many textbooks they use a function to compute the factorial of an integer using a recursive algorithm. Does anybody know if that is just because it is a nice example to illustrate recursion, or is it because the recursive implementation really has advantages? I mean, the non-recursive implementation using a for-loop seems more readable and uses less function calls.
I think it is the former of the two.
You're correct, factorial is a nice example of recursion, but a for loop will give you better performance.

The problem with recursion is that it's fine in cases where the recursion depth is relatively small. But recursion is not suitable when the call depth is very large. Every recursise call will push several registers plus the locals onto the stack. At some point, you're going to create a stack overflow, while a for loop maintains a fixed stack size.

This is not to say that recursion doesn't have it's place. There are a number of problems that are nicely solved using recursion. Look-ahead analysis in certain classes of games is one such example.
The problem is that not all compilers support the tail recursion. If a compiler supports the tail recursion a recursive factorial function can be as effective as a non-recursive function.
Topic archived. No new replies allowed.