(12) Recursion

(12) Recursion - Reading CMSC 132 Object-Oriented...

Info iconThis preview shows pages 1–3. Sign up to view the full content.

View Full Document Right Arrow Icon
1 CMSC 132: Object-Oriented Programming II Recursion Department of Computer Science University of Maryland, College Park 2 Reading Read Chapter 7 in the Koffman text (Chapter 5 in the second edition) 3 Recursion Recursion is a strategy for solving problems where a method calls itself The approach it uses is: if a problem instance is simple or trivial just solve it directly (called the base case ) else (called the recursive step ) 1. simplify the problem instance into smaller instance(s) of the same problem 2. solve the smaller instances using the same algorithm 3. combine the solution(s) to the smaller instances in a way that solves the original problem 4 Example – factorial Definition of the factorial function n! = n × n-1 × n-2 × n-3 × × 3 × 2 × 1 0! = 1 To calculate the factorial of n: Base case if n is 0, just return 1 Recursive step if n > 0 calculate the factorial of n-1 return n × (the factorial of n-1)
Background image of page 1

Info iconThis preview has intentionally blurred sections. Sign up to view the full version.

View Full DocumentRight Arrow Icon
5 Simulation of recursion (for factorial) 1. Get a number N from the person on your left 2. If it's 0, give 1 to the person on your left 3. Otherwise write N down 4. Decrement N and give the result to person on your right. Wait to receive a number M from them. 5. When you get M, give N * M to the person on your left 6 A more accurate simulation 1. Look at your desk 2. If there's one number there: if it's 0, lean over and write 1 on the desk on your left, move one seat to the left, and start over
Background image of page 2
Image of page 3
This is the end of the preview. Sign up to access the rest of the document.

This note was uploaded on 11/16/2011 for the course CMSC 132 taught by Professor Padua-perez during the Fall '08 term at Maryland.

Page1 / 5

(12) Recursion - Reading CMSC 132 Object-Oriented...

This preview shows document pages 1 - 3. Sign up to view the full document.

View Full Document Right Arrow Icon
Ask a homework question - tutors are online