{[ promptMessage ]}

Bookmark it

{[ promptMessage ]}

19-Recursion-Examples

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

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

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.

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

View Full Document
This is the end of the preview. Sign up to access the rest of the document.

{[ snackBarMessage ]}

### 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
Ask a homework question - tutors are online