Recursion provides elegant and simple
solutions to complex problems with minimal coding.
A recursive algorithm...
- calls itself inside its own definition.
- must have a stopping condition
which causes the algorithm to stop
Look at this example :
As the mathematicians will know, the factorial of an
integer is the product of that integer and all the integers less than it. It is
written n!.
So 5! = 5 x 4 x 3 x 2 x 1 = 120
The algorithm for working out the factorial of an integer
n can be written down in pseudocode as follows -
Factorial(n
: integer)
If n = 1 then
factorial = 1
else
factorial = n x factorial(n-1)
endif |
This uses the fact that n! = n x (n-1)!
Note :
- there is a stopping
condition (if n = 1 then...)
- the algorithm calls itself
inside its own definition.
|