Recursion 1. The computer science equivalent of mathematical induction. 2. A way of defining something in terms of itself. 3. Ex. f(n) = 1, if n ==1 f(n) = n + f(n - 1), if n > 1 =10 4. Ex. f(4) = 4 + f(3) = 6 f(3) = 3 + f(2) f(2) = 2 + f(1) = 3 f(1) = 1 5. f(4) = 4 + 3 + 2 + 1
7. Can we get the same output without recursion? 6. Note: this example of a recursive function is an arithmetic series. Σi = 1 i = (1 + n)n/2 n Ex. n = 6 1 + 2 + 3 + 4 + 5 + 6 = (1 + 6)(6/2) 7. Can we get the same output without recursion? 8. Yes. Always. Using loops. 9. Rewrite WhatItDo() without recursion. 10. Recursion shortens code but may take a great deal more computer time and space, sometimes causing “stack overflow”. Therefore, only use recursion when it helps solve a problem.