Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1of 13

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 Head Tree Nested


Type of Recursion

Direct Recursion a function calls itself from within itself 

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:

•Create a function towerOfHanoi where pass the N (current number of


disk), from_rod, to_rod, aux_rod.

•Make a function call for N – 1 th disk.


•Then print the current the disk along with from_rod and to_rod

•Again make a function call for N – 1 th disk.


TOH Algorithm
void towerOfHanoi(int n, char from_rod, char to_rod,
char aux_rod)
{
if (n == 0) {
return;
}
towerOfHanoi(n - 1, from_rod, aux_rod, to_rod);
cout << "Move disk " << n << " from rod " << from_rod
<< " to rod " << to_rod << endl;
towerOfHanoi(n - 1, aux_rod, to_rod, from_rod);
}

// Driver code
int main()
{
int N = 3;

// A, B and C are names of rods


towerOfHanoi(N, 'A', 'C', 'B');
return 0;
}
Examples
Find the value for A(1,2)

 
 

 Find the value of Q(2,3).


Thank You

You might also like