Unit Eight - Recursive Algorithms Flashcards

1
Q

Factorials

A

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)!

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

A recursive subroutine example

A

SUB calc(n)
If n = 0 then
factorial=1
else
facrorial= n*calc(n-1)
print (factorial)
EndSUB

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

How does it work?

A

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.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

Essential Characteristics of a recursive algorithm

A

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

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

The use of the call stack

A

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.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q
A
How well did you know this?
1
Not at all
2
3
4
5
Perfectly