{[ promptMessage ]}

Bookmark it

{[ promptMessage ]}

13-Recursion

# 13-Recursion - CS106X Autumn 2009 Handout 13 Recursion...

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

CS106X Handout 13 Autumn 2009 October 5 th , 2009 Recursion Today we'll start working with one of CS106X’s neatest ideas: recursion. Recursion often does the trick whenever the problem to be solved can be broken down into virtually identical (though smaller) sub-problems. The classic introductory example employing recursion is an implementation of the factorial function: int factorial(int n) { if (n == 0) return 1; return n * factorial(n - 1); } Every recursive function lists a sequence of base cases, and then one or more recursive cases. Occasionally, the problem to be solved is so simple that we can return or terminate execution without any further computation. The first of the two lines in factorial is an example of such a base case— factorial(0) is always 1 and is easily understood. However, whenever the specified integer n is larger than 0 , it helps to calculate factorial(n-1) and multiply the result of that computation by n itself. That's precisely what the recursive call is doing. We'll be spending the rest of this week and all of next week learning recursion. Recursion is difficult to understand the first time you see it, so be patient if it doesn’t click right away. I’ll be covering many of the examples covered in the reader, but I don’t reproduce those here. I do, however, have a good number of examples that aren’t in the reader, and that’s what this handout is all about. Go ahead and start reading through Chapters 5 and 6. Your third assignment is going out on Friday, and it’s all about recursion and recursive backtracking, so read!

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

View Full Document
2 Fractals I [Courtesy of Eric Roberts] Although fractals have been a mathematical curiosity for more than a century, modern interest in fractals as a practical tool can be traced largely to Benoit Mandelbrot, a researcher at IBM who made an extensive study of the field. As a way of getting people to understand the concept, Mandelbrot posed the following question: How long is the coastline of England? You can look up an answer in an encyclopedia, but that answer turns out to be meaningless unless
This is the end of the preview. Sign up to access the rest of the document.

{[ snackBarMessage ]}

### Page1 / 5

13-Recursion - CS106X Autumn 2009 Handout 13 Recursion...

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

View Full Document
Ask a homework question - tutors are online