Download Recursion in Computer Science: A University Course and more Exams Computer Science in PDF only on Docsity! Intro to Programming II Recursion Chris Brooks Department of Computer Science University of San Francisco Department of Computer Science — University of San Francisco – p. 1/?? 10-2: Recursion • 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: long factorial(int input) if (input == 1) return 1; else return input * factorial(input - 1); Department of Computer Science — University of San Francisco – p. 2/?? 10-5: Exercise: Fibonacci numbers • The Fibonacci numbers are defined as follows: f(0) = 0 f(1) = 1 f(n) = f(n − 1) + f(n − 2) • The first few numbers are 0,1,1,2,3,5,8,13,21,... • Write a class called Fibonacci. It should have a method called getFib(int n) that recursively calculates the nth Fibonacci number, plus a main method to test it. Department of Computer Science — University of San Francisco – p. 5/?? 10-6: Exercise: Fibonacci numbers • 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/?? 10-7: Recursion: Traversing a Maze • 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/?? 10-10: Recursion in graphics: Exercise • 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/?? 10-11: Fractals • 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/?? 10-12: Koch Snowflake: exercise • 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/??