14-Recursion

# 14-Recursion - CS106X Autumn 2010 Handout 14 October 1st,...

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

CS106X Handout 14 Autumn 2010 October 1 st , 2010 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, going out on October 6 th , 2010, will be all about recursion, and will include one of our most popular assignments: The Game of Boggle!

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
This is the end of the preview. Sign up to access the rest of the document.

## This note was uploaded on 01/13/2011 for the course CS 106X taught by Professor Cain,g during the Fall '08 term at Stanford.

### Page1 / 5

14-Recursion - CS106X Autumn 2010 Handout 14 October 1st,...

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

View Full Document
Ask a homework question - tutors are online