19-Recursion-Examples

19-Recursion-Examples - CS106X Winter 2008 Handout 19...

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

View Full Document Right Arrow Icon
CS106X Handout 19 Winter 2008 January 30, 2008 Introduction to Recursion Today we'll start working with one of CS106X’s neatest ideas: recursion. Recursion is 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); } Readings from the Text: Today's Lecture : Start Chapters 4 and 5. Friday’s Lecture : Continue with Chapters 4 and 5 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— 0! is always 1 and is easily understood. However, whenever the specified integer n is larger than 0 , it helps to calculate (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 a majority of next week learning recursion by example.
Background image of page 1

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

View Full DocumentRight Arrow Icon
Image of page 2
This is the end of the preview. Sign up to access the rest of the document.

This note was uploaded on 04/18/2008 for the course CS 106X taught by Professor Cain,g during the Winter '08 term at Stanford.

Page1 / 3

19-Recursion-Examples - CS106X Winter 2008 Handout 19...

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

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