moar_practice_no_ans

moar_practice_no_ans - 5 A Last-minute Introduction to...

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

View Full Document Right Arrow Icon
5 A Last-minute Introduction to Recursion A function that invokes itself is a recursive function. Consider the recursive factorial function below, which computes the value of the expression n ! : 1 int factorial( int n) 2{ 3 if (n <= 0) // Base case: 0! is 1 by definition; we don’t worry about negative values of n 4 return 1; 5 else 6 return n * factorial(n - 1); // Recursive case: n! = n * (n-1)! 7} This function works as we might expect; factorial(0) returns 1, factorial(1) returns 1, factorial(3) returns 6, and factorial(5) returns 120. A recursive function usually has an if block with a recursive case that invokes itself and a base case that speciFes where to stop. A through treatment of recursion is be- yond the scope of this practice exam. The important idea to note here is that it’s perfectly OK for a function to call itself. ±urthermore, we can use an if condition to control whether the function repeatedly calls itself or returns a base case value instead. 5.1 Comprehending Recursion What does factorial(6) return? Answer: How many calls to factorial does the expression factorial(8) cause? Answer: 5.2 Recursive Fibonacci Function Let’s now write a recursive function. Consider the sequence of Fibonacci numbers where the n th ±ibonacci number is equal to the sum of the two numbers in the ±ibonacci sequence that precede it. Let F n denote the n th ±ibonacci number. Then F n = F n 2 + F n 1 . The Frst eight ±ibonacci numbers are 0 , 1 , 2 , 3 , 5 , 8 , and 13 . Write a function int fib(int n) that returns the n th ±ibonacci number. ±or example, the expression fib(9) returns 21 and the expression fib(11) returns 55. You can write the function in 6 lines of code. 9
Background image of page 1

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

View Full DocumentRight Arrow Icon
6 More Classes, Structs, and Recursion (Oh My!) Part 1 Mark Zuckerberg (the CEO of Facebook) has asked you to help with a new Facebook App that stores peo- ple’s family trees. For each person who installs the App, the App ±nds that person’s parents, and the parents’ parents, etc, and creates that person’s family tree. Mark says the App will revolutionize the way people com- municate.
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 07/06/2011 for the course CS 31 taught by Professor Melkanoff during the Spring '00 term at UCLA.

Page1 / 8

moar_practice_no_ans - 5 A Last-minute Introduction to...

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