Recursion
Notes
- One more item for functions, recursion
- A recursive function is a function which calls itself
- In principal, there is nothing new.
- If we manage the stack properly, each instance of the function will have a unique memory
- And we can local variables in that memory.
- This is true in practice as well.
- Let's write a few recursive functions
- Power
- be = 1 if e is 0, or b*pow(b,e-1) otherwise
-
long Pow(long b,unsigned long e) { if (e == 0) { return 1 } else { return b * Pow(b, e-1); } }
- Fibonacci
- F(n) = 1, n=0,1 else F(n) = F(n-1) + F(n-2)
-
long Fib(unsigned long n) { if (n == 0 or n == 1) { return 0 } else { return Fib(n-1) + Fib(n-2) } }