Professional Documents
Culture Documents
INTRODUCTION TO
RECURSION
Instructor:
Ms.Dur-e-Shawar Agha
ROAD MAP
Introductionto recursion
Difference between iteration and recursion
Example of recursion
Tower of Hanoi
Recursion Tree
TYPES OF ALGORITHM
RECURSION
Any function which calls itself is called recursion.
OR
4!=4 * (3!)
=4 * (3 * (2!))
=4 * (3 * (2 * (1!)))
=4 * (3 * (2 * (1 * (0!))))
=4 * (3 * (2 * (1 * (1))))
RECURSION
Function
fac(4) = 4 * fac (3)
fac(0) = 1
Return
return 1 * 1 = 1
return 2 * 1 = 2
return 3 * 2 = 6
return 4 * 6 = 24
PRACTICE QUESTION
Find the output of the following recursive function
static int calc(int n) {
if (n==0)
return 0
else
return n + calc(n – 1);
}
calc (8) = ?
TOWER OF HANOI
The tower of Hanoi (also called the tower of Brahma or
the Lucas tower) was invented by a French
mathematician Édouard Lucas in the 19th century. It is
associated with a legend of a Hindu temple where the
puzzle was supposedly used to increase the mental
discipline.
Tower of Hanoi, is a mathematical puzzle which consists
of three towers (pegs) and more than one rings is as
depicted
TOWER OF HANOI
These rings are of different sizes and stacked upon in an
ascending order, i.e. the smaller one sits over the larger
one. There are other variations of the puzzle where the
number of disks increase, but the tower count remains
the same.
2 DISCS OF TOWER OF HANOI
Step 1: Move disc 1 from pole A to pole B.
Step 2: Move disc 2 from pole A to pole C.
Tower of Hanoi
Recursion Tree