Introduction to Computer Science - Alice Recursion Introduction to Computer Science - Alice
Sample code on conditional loops
What do these images have in common?
They are all RECURSIVE
Recursion is common in math Factorial numbers n! = 1*2*3*...*(n-2)*(n-1)*n Power Series Taylor Series Fibonacci Sequence 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, … (keep adding preceding two numbers)
Example of Recursion Fibonacci sequence shown as a graph
Another example of recursion - Towers of Hanoi Move the discs from one position to another, where an upper disc must always be smaller than the lower discs
Recursion is... In math, an object is defined by itself In computer science, a function calls itself Need a condition to cause the function to stop calling itself
Applications of recursion in computer science Sorting data Solving tree structure algorithms Drawing fractals Calculating mathematical series, which in turn are used to approximate functions in computer calculations
Sample code for Fibonacci fibonacci(n) ....if n == 0 ........return 0 ....else if n ==1 ........return 1 ....else .......return fibonacci(n-1) + fibonacci(n-2)
Recursion vs Conditional-Loops When do you use one over the other? Conditional loops require less memory and therefore run faster and are easier to read Recursion is better when The condition to end a repetitive behavior is made up of multiple factors, for example a horse race or Towers of Hanoi For mathematical series