Recursion isn't simply a matter of a function calling itself over and over again. There is a fairly precise definition of recursion, which says, according to wikipedia: a method where the solution to a problem depends on solutions to smaller instances of the same problem.
Recursion calls for a "base case" that returns the final value.
Prototypical examples include factorial, which I'm kind of surprised Cragoo didn't use, since it is very good for ternary operations. where the base case is 0! = 1:
Code:
function factorial (x)
return x == 0 ? 1 : x * factorial (x - 1)
Another recursive problem is a palindrome.
Is "hannah" a palindrome?
is "anna" a palindrome?
is "nn" a palindrome?
is the final result "": return true.
A binary tree:
If you go left, you still have a binary tree
Go right, you still have a binary tree.
Base case: you've reached a node.
Recursion can be difficult because it is not always obvious what the base case should be, and it is not always obvious that a problem can be broken down into successively smaller pieces of the same problem. For example, I don't find it intuitively obvious that the Tower of Hanoi can be broken down into a simple and repeating algorithm of moving pegs. The base case, no more moves possible, is obvious.
There are variations on what the base-case is. In successive approximation and fixed point algorithms, the base case is actually epsilon (a margin of error).
It isn't always obvious that certain algorithms don't need an epsilon and will complete if given any input and enough time. A classic example is the
Ackermann Function.
Recursion is based off of recurrences (hence the similar name), and it isn't always intuitively obvious how to even get started and even how to end. Heck, some aren't even intuitively obvious they can be recursive in the first place. See Concrete Mathematics for a slew of examples.
Some recursion requires memoization, hence dynamic programming.
Recursion and iteration are very different at the stack level.
Did I forget to mention TCO?
Recursion is not easy. It is pretty deep stuff.