

Study with the several resources on Docsity
Earn points by helping other students or get them with a premium plan
This page cannot be seen from the preview
Don't miss anything!


Chris Brooks Department of Computer Science University of San Francisco ?? Department of Computer Science — University of San Francisco – p.1/
Recursion is a fundamental problem-solving technique Involves decomposing a problem into: A base case that can be solved directly A recursive step that indicates how to handle more complex cases. A common recursive example is factorial: input) factorial(int long
A more interesting example is the Towers of Hanoi. It’s hard to write an iterative program to solve this, but the recursive version is startlingly simple: tempTower) Tower goalTower, Tower startTower, Tower ndisks, towers(int void
A common error in recursion is forgetting the base case. infinite recursion This can lead to input) factorial(int double 1); - factorial(input * input return This eill eventually have a stack overflow. ?? Department of Computer Science — University of San Francisco – p.4/
The Fibonacci numbers are defined as follows:
What is a problem with the naive way of implementing Fibonacci? Can you think of a way around this? How would you implement Fibonacci iteratively? ?? Department of Computer Science — University of San Francisco – p.6/
Solving a maze is the sort of problem that requires trial-and-error. When you’re stuck, back up and undo the last thing you did. This sort of approach works well with recursion. We’ll represent the maze as a two-dimensional array. 1 = clear, 0 = blocked. Start in the upper left, get to the lower right. ?? Department of Computer Science — University of San Francisco – p.7/
Change the rules so that you always try to go left, then right, then up, then down. Write a Maze constructor that takes two arguments: row and col and generates a random maze of that size. ?? Department of Computer Science — University of San Francisco – p.8/
We can use recursion to easily create interesting graphical effects. For example, recursively tiling a surface. ?? Department of Computer Science — University of San Francisco – p.9/
Add your own pictures to the applet. Change the applet so that the recursive part of the picture is in the lower right. ?? Department of Computer Science — University of San Francisco – p.10/
We can also use recursion to draw fractals Example: Koch snowflake Rule: Each line segment is replaced by a “wedge” with sides that are the same length as the replaced piece. As we increase the depth, it begins to look like a snowflake. ?? Department of Computer Science — University of San Francisco – p.11/
Change the color scheme of the applet. Change the default max and min values Change the initial triangle to have its “point” downward. ?? Department of Computer Science — University of San Francisco – p.12/