- What is recursion?
- A recursive program is a program which calls itself, usually it calls itself on a problem with smaller size.
- Be careful - if not done correctly, this can lead to infinite recursion!
-
Related to mathematical induction:
- To prove a statement for a problem of size N:
- Base case: Prove the problem for small N (usually 0 or 1)
- Induction step:
- Assume true for size N-1
- Prove it is true for size N
- Example: use method to prove T(N)= 1 + 2 + 3 + ... + N = N (N+1)/2 for all N
- Base case: T(1) = 1 = 1 (1+1)/2
- Induction step: T(N) = N + T(N-1) = N + (N-1)(N)/2 = ... = N (N+1)/2
- Assume true for T(N-1)
- Prove it is true for size N-1
-
Problems which lend themselves to recursive solutions are generally problems with the properties:
-
Examples: Printing an array, calculating factorial or the Fibonacci Series
- Factorial n! = 1*2*3* ... *(n-1)*n
What is the base case and what is the recursion?
- Other examples can be seen on lab for CS-145.
- Fractals and recursion