Docsity

Recursion in Computer Science: A University Course, Exams of Computer Science

Partial preview of the text

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/

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 complexcases. - 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/

Infinite recursion

  • A common error in recursion is forgetting the base case. - This can lead to infinite recursion double factorial(int input) return input * factorial(input - 1); - This will eventually have a stack overflow. Department of Computer Science โ€” University of San Francisco โ€“ p. 4/

Exercise: Fibonacci numbers

  • The Fibonacci numbers are defined as follows: f

f

f

n

f

n

f

n

  • The first few numbers are 0,1,1,2,3,5,8,13,21,... - Write a class called Fibonacci. It should have a method calledgetFib(int n) that recursively calculates the nth Fibonaccinumber, plus a main method to test it. Department of Computer Science โ€” University of San Francisco โ€“ p. 5/

Recursion: Traversing a Maze

  • Solving a maze is the sort of problem that requirestrial-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/

Exercise: Solving a maze

  • 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 andcol and generates a random maze of that size. Department of Computer Science โ€” University of San Francisco โ€“ p. 8/

Recursion in graphics: Exercise

  • Add your own pictures to the applet. - Change the applet so that the recursive part of the picture is inthe lower right. Department of Computer Science โ€” University of San Francisco โ€“ p. 10/

Fractals

  • We can also use recursion to draw fractals - Example: Koch snowflake - Rule: Each line segment is replaced by a โ€œwedgeโ€ with sidesthat 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/