This preview shows pages 1–3. Sign up to view the full content.
Recursion
Mirror, mirror on the wall
2

29
[CS1102C AY0809S2 Lecture 5]
Lecture Outline
±
Recursion  Basic idea
±
Iteration versus Recursion
±
How recursion works
±
Recursion  How to
±
More examples on recursion
²
Printing a LinkedList
²
Printing a LinkedList in reverse
²
Choose k out of n things
²
Tower of Hanoi
²
Fibonacci Numbers
3

29
[CS1102C AY0809S2 Lecture 5]
Recursion : The Basic Idea
±
The process of solving a problem with a
function that
calls itself
directly or indirectly
²
The solution can be derived from solution of smaller
problem of the same type
±
Example:
²
Factorial(4)
= 4 *
Factorial (3)
±
This process can be repeated
²
E.g.
Factorial(3)
can be solved in term of
Factorial(2)
±
Eventually, the problem is so simple that it can solve
immediately
²
E.g.
Factorial(0) = 1
±
The solution to the larger problem can then be derived
from this …
4

29
[CS1102C AY0809S2 Lecture 5]
Recursion: The Main Ingredients
±
To formulate a recursive solution:
²
Identify the “
simplest
” instance
(The
base case
: so that we can solve it
without
recursion)
²
Identify “
simpler
” instances of the same
problem
(The
recursive case
: so that we can make
recursive calls to solve them)
±
Identify how the solution from the simpler problem can
help to construct the final result
²
Be sure we are able to reach the “
simplest
”
instance
±
So that we will not get an
infinite recursion
This preview has intentionally blurred sections. Sign up to view the full version.
View Full Document 5

29
[CS1102C AY0809S2 Lecture 5]
Example : Factorial
±
Lets write a recursive function
factorial(k)
that finds
k!
²
Base Case:
±
Return
1
when
k = 0
±
Corresponds to this bit of C/C++ code:
if( k == 0 )
return 1;
²
Recursive Case:
±
Return
k * (k1)!
return k * factorial(k1);
6

29
[CS1102C AY0809S2 Lecture 5]
Example : Factorial (code)
±
Full code for
factorial
:
long factorial(int k)
{
if ( k == 0 )
return 1;
else
return k * factorial(k1);
}
Base Case:
factorial( 0 ) = 1
Recursive Case:
factorial( k ) =
k * factorial( k – 1)
7

29
[CS1102C AY0809S2 Lecture 5]
Understanding Recursion
±
A recursion always goes through two phases:
²
A windup phase:
±
When the
base case
is
not
satisfied i.e. the function
calls itself
±
This phase carries on
until
we reach the
base case
²
An unwind phase:
±
This is the end of the preview. Sign up
to
access the rest of the document.
This note was uploaded on 12/02/2011 for the course CS 3211 taught by Professor Dunnowho during the Spring '11 term at National University of Singapore.
 Spring '11
 dunnowho
 Recursion

Click to edit the document details