Presentation is loading. Please wait.

Presentation is loading. Please wait.

Chapter 1 Introduction Recursion

Similar presentations


Presentation on theme: "Chapter 1 Introduction Recursion"— Presentation transcript:

1 Chapter 1 Introduction Recursion
Section 1.3

2 Recursion Recursive function Base Case Recursive Call
A function that is defined in terms of itself E.g. f(0)=0 and f(x) = 2f(x-1)+x2 Implementation in C or C++ Base Case Recursive Call

3 Recursion Examples Example: evaluation of f(x) = 2f(x-1)+x2
What proof technique will you use to prove g(N) = N2? g(1) = 1 g(k) = 2k g(k-1), k > 1 Bookkeeping Backtrack

4 Recursion and the Program Stack
void reverse() { char ch; cin.get(ch); if(ch != ‘\n’) reverse(); cout.put(ch); } Input: ABC’\n’ ch = ‘\n’ (to 204) Line 201 ch = ‘C’ (to 204) Line 202 Output: C ch = ‘B’ (to 204) Line 203 Output: B Line 204 ch = ‘A’ (to main) Output: A 4 4

5 Write Recursive Code p(x, 0) = 1 p(x, n) = x·p(x, n-1), n > 0
(to 203) Return value = float power(float x, unsigned int n ) { if(n==0) return 1.0; else return x*power(x, n-1); } main: y = 1 + 3*power(2.0,2); 1 x = 2 n = 1 (to 203) Return value = Line 201 Line 202 2 x = 2 n = 2 (to 100) Return value = Line 203 4 Line 100 5 5

6 Ensuring Recursive Programs Terminate
What happens if you make the call f(-1) in the implementation of f(x) = 2f(x-1)+x2 ? Another non-terminating recursive function What happens on call to bad(1)? And bad(2)? And bad(3)?

7 Making sure recursive programs terminate (contd.)
Two rules for writing correct recursive programs Define a base case This is what terminates recursion Make progress At each step make progress towards the base case More rules for writing clean and efficient recursive programs Design rule Assume that all recursive calls work. Compound interest rule Never duplicate work by making same recursive call twice! E.g. Fibonacci series f(i) = f(i-1) + f(i-2). Why??

8 Example Code Code examples are in the following directory on the CS file server ~cop4530/fall11/examples/Lec2 Implementation of Fibonacci numbers examples/Lec2/fibonacci_recursive.cpp examples/Lec2/fibonacci_nonrecursive.cpp Compare the running times of these programs Experiment with the other code examples Can you explain what reverse2.cpp does?


Download ppt "Chapter 1 Introduction Recursion"

Similar presentations


Ads by Google