# Introduction Recursion Section 1.3 Chapter 1

```Chapter 1
Introduction
Recursion
Section 1.3
1
Recursion
• Recursive function
– 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
2
Recursion Examples
• Example: evaluation of f(x) = 2f(x-1)+x2
– f(4) = 2*f(3) + 4*4
• f(3) = 2*f(2) + 3*3
Bookkeeping
– f(2) = 2*f(1) + 2*2
&raquo; f(1) = 2*f(0) + 1*1
&raquo;
f(0) = 0
&raquo; f(1) = 2*0 + 1*1 = 1
– f(2) = 2*1 + 2*2 = 6
Backtrack
• f(3) = 2*6 + 3*3 = 21
– f(4) = 2*21 + 4*4 = 58
• What proof technique will you use to prove g(N) = N2?
– g(1) = 1
– g(k) = 2k - 1 + g(k-1), k &gt; 1
3
Recursion and the Program Stack
• void reverse()
{
Line 201
Line 202
Line 203
Line 204
char ch;
cin.get(ch);
if(ch != ‘\n’)
{
reverse();
cout.put(ch);
}
}
ch = ‘\n’
(to 204)
ch = ‘C’
(to 204)
Output: C
ch = ‘B’
(to 204)
Output: B
ch = ‘A’
(to main)
Output: A
• Input: ABC’\n’
4
Write Recursive Code
• p(x, 0) = 1
• p(x, n) = x&middot;p(x, n-1), n &gt; 0
• float power(float x, unsigned
int n )
{
Line 201
Line 202
if(n==0)
return 1.0;
else
return x*power(x, n-1);
Line 203
}
Line 100 main: y = 1 + 3*power(2.0,2);
x=2
n=0
(to 203)
Return value = 1
x=2
n=1
(to 203)
Return value = 2
x=2
n=2
(to 100)
Return value = 4
5
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
6
Making sure recursive programs terminate
(contd.)
•
Two rules for writing correct recursive programs
1.
Define a base case
•
2.
Make progress
•
•
This is what terminates recursion
At each step make progress towards the base case
More rules for writing clean and efficient recursive
programs
3.
Design rule
•
4.
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??
7
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?
8
```