For example, the mathematical operation "factorial" can be defined iteratively (for n! multiply all numbers from 1 to n) or it can be defined recursively (n!=n*(n-1)! and 1!=1).

To write a recursive algorithm for n! you could write:

int factorial(int n)

{ if(n==1)return(1);

return(factorial(n-1));

}

This can work because of the stack driven nature of method calls. When factorial is called the value for the argument n is put on the stack, and then the JVM jumps to the code for factorial. If factorial needs to call itself it pushes the new "n" onto the stack, and jumps to the start of the method, just as before. As the methods returns, the stack "unwinds", and eventually, it pops out the answer to the original caller.

The solution to the towers of Hanoi problem is also usually phrased in a recursive fashion. You have three sticks (1, 2 and 3). On stick one there is a number of rings of diminishing size. You must get them onto stick 3 without ever putting a larger on a smaller ring. So, for one ring the solution is simple: move the ring from 1 to 3. For 2 rings it is also simple: move the top ring to 2, move the bottom ring to 3, then move the top ring to 3: done.

However, the solution for 2 rings (or any number) could also be phrased: Move all but the bottom ring to stick 2. Then move the bottom ring to 3. Then move the rings on 2 to 3. And the process for the first and last operation is the same, except for one less ring.