Unit Eight - Recursive Algorithms Flashcards
Factorials
E.g. 5! = 5x4x3x2x1
The factorial function is a good example of a function that is defined in terms of itself. n!= n x (n-1)!
A recursive subroutine example
SUB calc(n)
If n = 0 then
factorial=1
else
facrorial= n*calc(n-1)
print (factorial)
EndSUB
How does it work?
Each time the subroutine is called, the return address, parameter and local variables are pushed onto the stack. Statement 6 is not reached until the routine is called with n=0, when 0!=1 is output. Then statement seven is reached so the next return address (6) is popped.
Essential Characteristics of a recursive algorithm
There must be a stopping condition or base case so that when its met it will not call itself so it can start unwinding.
For all vales other than the base case, the routine must call itself
You must be able to reach the base case within a finite number of calls
The use of the call stack
Every time the subroutine is called, the return address (the line after CALL statement) is put on the call stack. Even with a stopping conditions, the recursive routine can only be called for a limited number of times or the stack will overflow the maximum memory capacity.