Possible Duplicate:
Can every recursion be converted into iteration?
Can always or which cases a recursive function be converted into a non-recursive function or set of non-recursive functions?
Can you point me to examples which work and do not work?
Thanks
This is always possible, because you can emulate the call stack yourself. However, it’s not always easy to do.
The easy cases are tail recursion: these don’t even require a stack. For example, this guy is trivially converted into a
forloop:Even if the function is not strictly tail-recursive, you can sometimes still get away without a stack. For example, the classical factorial function:
It gets harder when there are multiple recursive calls. Consider, for example, quicksort:
Although it’s definitely possible to do this without recursion, you’ll have to build a stack yourself, and construct a
whileloop that iterates until the stack is empty.