Recursion
Mirror, mirror on the wall
2
---
71
[CS1102C AY0708S1 L5]
Lecture Outline
Recursion - Basic idea
Iteration versus Recursion
How recursion works
Recursion - How to
More examples on recursion
Printing a Linked-List
Printing a Linked-List in reverse
Choose k out of n things
Tower of Hanoi
Fibonacci Numbers
3
---
71
[CS1102C AY0708S1 L5]
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
---
71
[CS1102C AY0708S1 L5]
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

**sections.**

*blurred***to view the full version.**

*Sign up*