3/24/2013
Structured Programming Using C++ Lecture 6 : Recursive functions
Dr. Amal Khalifa Dr. Safwat Hamad
Lecture Contents:
Recursive void Functions
Recursive Functions that Return a Value
Tracing recursive calls Infinite recursion, overflows Powers function
Thinking Recursively
Recursive design techniques
Dr. Hamad, Dr. Khalifa 13-2
Dr. Amal Khalifa - Spring 2012
1
3/24/2013
Introduction to Recursion
A function that "calls itself"
Said to be recursive In function definition, call to same function
Divide and Conquer
Basic design technique Break large task into subtasks Subtasks could be smaller versions of the original task! Example: Computing global sum of a list
Dr. Hamad, Dr. Khalifa 13-3
Example •Subtask •
Compute sum for 1st half of list
•Subtask •
38
27
43
3
9
82
10
20
1:
2:
Compute sum for 2nd half of list
•Eg:
{38, 27, 43, 3, 9, 82, 10, 20}
13-4
Dr. Amal Khalifa - Spring 2012
Dr. Hamad, Dr. Khalifa
2
3/24/2013
Example : Recursive void Function
Write a function that prints a message a specified number of times. Hint: write two versions one iterative and the other recursive.
5
Dr. Hamad, Dr. Khalifa
Recursion—A Closer Look
Computer tracks recursive calls
Stops current function
Must know results of new recursive call before proceeding
Saves all information needed for current call
To be used later
Proceeds with evaluation of new recursive call
When THAT call is complete, returns to "outer" computation
Dr. Hamad, Dr. Khalifa
Dr. Amal Khalifa - Spring 2012
3
3/24/2013
Recursion Big Picture
Outline of successful recursive function:
One or more cases where function accomplishes it’s task by:
Making one or more recursive calls to solve smaller versions of original task
Called "recursive case(s)"
One or more cases where function accomplishes it’s task without recursive calls
Called "base case(s)" or stopping case(s) Base case MUST eventually be entered If it doesn’t Recursive calls never end! infinite recursion Dr. Hamad, Dr. Khalifa 13-7
Example : Vertical Numbers Write a function writeVertical(num) that displays the digits of given number vertically, one per line. Example : >>1234 1 2 3 4 8
Dr. Amal Khalifa - Spring 2012
Dr. Hamad, Dr. Khalifa
4
3/24/2013
Recursive Definition
Break problem into two cases
Simple/base case:
Recursive case:
if n<10 write number n to screen if n>=10 two subtasks:
1- Output all digits except last digit 2- Output last digit
Example: argument 1234:
1st subtask displays 1, 2, 3 vertically 2nd subtask displays 4
13-9
Dr. Hamad, Dr. Khalifa
Function Tracing !! void writeVertical(int n) { if (n < 10) //Base case cout << n << endl; else { //Recursive step writeVertical(n/10); cout <<(n%10)<
13-10
Dr. Amal Khalifa - Spring 2012
writeVertical(123)
writeVertical(12)
writeVertical(1)
cout << 1 << endl;
cout << 2 << endl;
cout
<< 3 << endl;
•What
happens if base case omitted??
Dr. Hamad, Dr. Khalifa
5
3/24/2013
Stacks for Recursion
A stack
Specialized memory structure Like stack of paper
Place new on top Remove when needed from top
Called "last-in/first-out" memory structure
Recursion uses stacks
Each recursive call placed on stack When one completes, last call is removed from stack
Dr. Hamad, Dr. Khalifa 13-11
Stack Overflow
Size of stack limited
Long chain of recursive calls continually adds to stack
All are added before base case causes removals
If stack attempts to grow beyond limit:
Memory is finite
Stack overflow error
Infinite recursion always causes this
Dr. Hamad, Dr. Khalifa 13-12
Dr. Amal Khalifa - Spring 2012
6
3/24/2013
Recursion Versus Iteration
Recursion not always "necessary" Not even allowed in some languages Any task accomplished with recursion can also be done without it
Nonrecursive: called iterative, using loops
Recursive:
Runs slower, uses more storage Elegant solution; less coding
Dr. Hamad, Dr. Khalifa 13-13
It’s break time!! See you…..
14
Dr. Amal Khalifa - Spring 2012
Dr. Hamad, Dr. Khalifa
7
3/24/2013
Recursive Functions with return Recursion not limited to void functions Can return value of any type Same technique, outline:
1.
One+ cases where value returned is computed by recursive calls
2.
Should be "smaller" sub-problems
One+ cases where value returned computed without recursive calls
Base case
Dr. Hamad, Dr. Khalifa 13-15
base exp = base * base exp-1
Recursive power()
int power (int x, int n)
function power(base, p):
{
if (n<0) { cout << "Illegal argument"; exit(1); } if (n>0) return (power(x, n-1)*x); else return (1); }
13-16
Dr. Amal Khalifa - Spring 2012
Returns base raised to p Returns double value power(x, n – 1) * x power(2,3); power(2,2)*2 power(2,1)*2 power(2,0)*2 1
Dr. Hamad, Dr. Khalifa
8
3/24/2013
Tracing Function power(2,3)
13-17
Dr. Hamad, Dr. Khalifa
Thinking Recursively
Ignore details
Forget how stack works Forget the suspended computations Yes, this is an "abstraction" principle! And encapsulation principle!
Let computer do "bookkeeping"
Programmer just think "big picture"
Dr. Hamad, Dr. Khalifa 13-18
Dr. Amal Khalifa - Spring 2012
9
3/24/2013
Recursive Design Techniques
Don’t trace entire recursive sequence! Just check 3 properties: 1. 2. 3.
No infinite recursion Stopping cases return correct values Recursive cases return correct values
Dr. Hamad, Dr. Khalifa 13-19
Recursive Design Check: power()
Check power() against 3 properties: 1.
No infinite recursion:
2.
3.
2nd argument decreases by 1 each call Eventually must get to base case of 1
Stopping case returns correct value:
power(x,0) is base case
Returns 1, which is correct for x0
Recursive calls correct:
For n>1, power(x,n) returns power(x,n-1)*x
Plug in values correct
Dr. Hamad, Dr. Khalifa 13-20
Dr. Amal Khalifa - Spring 2012
10
3/24/2013
Example: factorials Write a function factorial(num) that recursively computes the factorial of an integer. Hint : N! = 1 x 2 x 3 x 4 ……(N-1) x N
21
Dr. Hamad, Dr. Khalifa
That’s all for today !! Thanks…..
22
Dr. Amal Khalifa - Spring 2012
Dr. Hamad, Dr. Khalifa
11