lecture_21_revised

lecture_21_revised - 1 lecture_21.txt 2010-11-02 10:25...

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

View Full Document Right Arrow Icon

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

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

Unformatted text preview: 1 lecture_21.txt 2010-11-02 10:25 David Nicol Recursion Read at home Chapter 17 Definitions------------ A recursive task is one that calls itself.- with each invocation a "smaller" problem is presented for solution- eventually a "base case" that cannot be reduced is reached. - the condition which selects the base case is the "terminal condition" Each recursive task has two characteristics :- the task is defined in terms of itself, combining smaller solutions of itself- the task has a terminal case whose solution is NOT recursive, e.g., the solution does not depend on calling the task again on a smaller problem Example 1 : Factorial---------------------- Recall that N! = N*(N-1)*(N-2)* ... *2*1 for N>1. Customary to DEFINE 0! = 1 Notice that 4! = 4 * 3! ah ha! recursion So a recursive definition of factorial is N! = 1 if N=1 N*(N-1)! if N>1 So here the function is defined in terms of itself, and has a terminal condition (N=1) and a base case. Now think about the steps involved when evaluating 4! recursively 4! -> remember 4, x call 3! remember 3, x 2! remember 2, x 1! value 1 2 = 2 x 1 6 = 3 x 2 24 = 4 x 6 24 Recursive factorial in C------------------------- int factorial(int number) ; int factorial(int number) { if(number == 0) return 1; if(number == 1) return 1; return number*factorial(number-1); } Runtime stack for factorial(4) main() { int f4 = factorial(4); 2 lecture_21.txt 2010-11-02 10:25 David Nicol } A RECURSIVE CALL IS LIKE ANY OTHER SUBROUTINE CALL, SO A STACK FRAME IS CREATED FOR EACH CALL----------------- factorial(1) <- R6----------------- factorial(2)----------------- factorial(3)----------------- factorial(4)----------------- main------------------ where each stack frame above has the usual format Another example : Fibonacci Numbers A sequence of numbers F(n), in which each number is the sum of the previous two numbers : Define F(0) = 0, F(1) = 1 n= 0 1 2 3 4 5 6 7 8 F(n) 0 1 1 2 3 5 8 13 21 ......
View Full Document

Page1 / 6

lecture_21_revised - 1 lecture_21.txt 2010-11-02 10:25...

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