Professional Documents
Culture Documents
Recursion
Recursion
Types of Recursion
Lecture 7
Tower of Hanoi
Recursion
Any procedure containing either a call statement to itself or a call statement to a
second procedure that may eventually result in a call statement back to the original
procedure.
Properties:
There must be a certain criteria, called base criteria for which the procedure does not
call itself.
Each time the procedure does call itself (directly or indirectly) it must be closer to the
base criteria.
Types of Recursion
Recursion
Direct Indirect
Tail Recursion If a recursive function calling itself and that recursive call is the last
statement in the function then it’s known as Tail Recursion.
Head Recursion If a recursive function calling itself and that recursive call is the first
statement in the function then it’s known as Head Recursion.
Tree Recursion If a recursive function calling itself for more than one time then it’s known
as Tree
Nested Recursion a recursive function will pass the parameter as a recursive call. That
means “recursion inside recursion”.
Indirect Recursion there may be more than one functions, and they are calling one another in a circular manner.
Tower of Hanoi
Tower of Hanoi is a mathematical puzzle where we have three rods (A, B, and C) and N disks.
Initially, all the disks are stacked in decreasing value of diameter i.e., the smallest disk is placed on
the top and they are on rod A. The objective of the puzzle is to move the entire stack to another rod
(here considered C), obeying the following simple rules:
Rules:
•Only one disk can be moved at a time.
•Each move consists of taking the upper disk from one of the stacks and placing it on top of another
stack i.e. a disk can only be moved if it is the uppermost disk on a stack.
•No disk may be placed on top of a smaller disk.
Tower of Hanoi
A B C A B C A B C A B C
A B C A B C A B C A B C
Tower of Hanoi
Follow the steps below to solve the problem:
// Driver code
int main()
{
int N = 3;