DSOOP (CO 221) 
B.Tech 4th Sem (ECE and ME)
Recursion 
Def: The idea of one function calling itself 
Example Problems: 
Factorial 
Fibonacci Series 
Towers of Hanoi
Factorial using Recursion 
• #include<stdio.h> long factorial(int n) 
• { 
• long factorial(int); if (n == 0) 
• return 1; 
• int main() else 
• { return(n * factorial(n-1)); 
int num; } 
• long f; 
• 
• printf("Enter a number to ffiinndd ffaaccttoorriiaallnn""));; 
• scanf("%d", &num); 
• 
• if (num < 0) 
• printf("Negative numbers are not allowed.n"); 
• else 
• { 
• f = factorial(num); 
• printf("%d! = %ldn", num, f); 
• } 
• return 0; 
• }
Fibonacci using Recursion 
• #include<stdio.h> int Fibonacci(int n) 
• { 
• int Fibonacci(int); if ( n == 0 ) 
» 
• main() return 0; 
• { else if ( n == 1 ) 
• int n, i = 0, c; return 1; 
• else 
• scanf("%d",&n); return ( Fibonacci(n-1) + Fibonacci(n-2) ); 
• printf("Fibonacci sseerriieessnn""));; }} 
• 
• for ( c = 1 ; c <= n ; c++ ) 
• { 
• printf("%dn", Fibonacci(i)); 
• i++; 
• } 
• 
• return 0; 
• }
Towers of Hanoi 
A mathematical game or puzzle. 
Also known as Lucas Tower or Towers of Brahma. 
Components: 
 3 rods or pegs 
 Number of disks of various sizes
Origin 
 Invented by French Mathematician, Edouard 
Lucas in 1883 
 Indian Temple with 3 posts 
 64 golden disks 
 264-1 moves or seconds, one move per second, 
roughly 585 billion years i.e. 
18,446,744,073,709,551,615 moves
Rules for Lucas Tower 
• You can move only one disk at a time. 
• Each move consists of taking the upper disk 
from one of the rods and sliding it onto 
another rod, on top ooff tthhee ootthheerr ddiisskkss tthhaatt 
may already be present on that rod. 
• No disk may be placed on top of a smaller 
disk. 
• Video simulation-
Computational Time or Solution 
n – number of disks 
Number of moves required to solve the puzzle 
f(n)= 2n - 1
a) The initial state; b) move n - 1 disks from A to C
c) move one disk from A to B; d) move n - 1 disks from C to B
The Recursion Tree
The Recursive Algorithm 
MoveTower (N, Beg, Aux, End) 
1. If n=1, then; 
(a) Write: Beg - End 
(b) Return 
[EEnndd ooff IIff SSttrruuccttuurree]] 
2. Move n-1 disks from peg/pole Beg to peg/pole Aux 
Call MoveTower(n-1,Beg,End,Aux) 
3. Write Beg- End 
4. Move n-1 disk from peg /pole Aux to peg/pole End 
Call MoveTower(n-1, Aux, Beg, End) 
5. Return
MoveTower(3,A,B,C) 
MoveTower(2,A,C,B) MoveTower(2,B,A,C) 
MoveTower(1,A,B,C) MoveTower(1,C,A,B) MoveTower(1,B,C,A) MoveTower(1,A,B,C) 
A - C A -B C - B A - C B - A B - C A - C 
A B C A B C A B C A B C 
Initial State (1) A - C (2) A - B (3) C - B 
A B C A B C A B C A B C 
(4) A - C (5) B - A (6) B - C (7) A - C
MoveTower(3,A,B,C) 
MoveTower(2,A,C,B) MoveTower(2,B,A,C) 
MoveTower(1,A,B,C) MoveTower(1,C,A,B) MoveTower(1,B,C,A) MoveTower(1,A,B,C) 
A - C A -B C - B A - C B - A B - C A - C 
A B C A B C A B C A B C 
Initial State (1) A - C (2) A - B (3) C - B 
A B C A B C A B C A B C 
(4) A - C (5) B - A (6) B - C (7) A - C
Recursion Disadvantage 
• Recursive algorithms have more overhead than similar 
iterative algorithms 
– Because of the repeated method calls (storing and removing 
data from call stack) 
– This may also cause a “stack overflow” when the call stack 
ggeettss ffuullll 
• It is often useful to derive a solution using recursion and 
implement it iteratively 
– Sometimes this can be quite challenging! 
(Especially, when computation continues after the recursive 
call - we often need to remember value of some local 
variable - stacks can be often used to store that 
information.)
Recursion Disadvantage 
• Some recursive algorithms are inherently inefficient 
• An example of this is the recursive Fibonacci algorithm 
which repeats the same calculation again and again 
– Look at the number of times fib(2) is called 
• Even if the solution was determined using rreeccuurrssiioonn ssuucchh 
algorithms should be implemented iteratively 
• To make recursive algorithm efficient: 
– Generic method (used in AI): store all results in some data 
structure, and before making the recursive call, check whether 
the problem has been solved. 
– Make iterative version.
Function Analysis for call fib(5) 
5 
fib(5) 
3 2 
fib(4) fib(3) 
int fib(int n) 
if (n == 0 || n == 1) 
return n 
else 
return fib(n-1) + fib(n-2) 
fib(3) fib(2) 
fib(2) fib(1) 
fib(1) fib(0) 
fib(1) fib(0) 
fib(2) 
fib(1) 
fib(1) fib(0) 
1 
1 1 1 
1 
0 0 
0 
1 
2 1 1
Assignment 1 
• Write the program for Tower of Hanoi in C++ using linked lists 
using recursion. 
Submission: Within FFeebbrruuaarryy 22001144
References for Towers of Hanoi 
• Data Structures by Seymor Lipschutz 
• http://en.wikipedia.org/wiki/Tower_of_Hanoi
Divide and Conquer Algorithms 
Definition: For a problem P associated with a set S, if A 
is an algorithm which partitions S into smaller sets such 
that the solution of the problem P for S is reduced to 
the solution of P for one or more of the smaller sets. 
Then A is called a Divide and CCoonnqquueerr aallggoorriitthhmm. 
Algorithms: 
 Quick Sort Algorithm 
 Binary Search Algorithm
(Quick Sort) This algorithm sorts an array A with N elements. 
1. [Initialize] TOP:=NULL 
2. [Push boundary values of A onto stacks when A has 2 or more elements.] 
If N1, then :TOP:=TOP+1, LOWER[1]:=1,UPPER[1]:=N. 
3. Repeat Steps 4 to 7 while TOP!=NULL. 
3. [Pop sublist from stacks.] 
Set BEG:=LOWER[TOP], END:=UPPER[TOP], 
TOP:=TOP-1. 
5. Call QUICK(A,N,BEG,END,LOC) 
6. [Push left sublist onto stacks when it has 2 or more elements.] 
IIff BBEEGGLLOOCC-11,, tthheenn :: 
TOP:=TOP+1, LOWER[TOP]:=BEG, 
UPPER[TOP]=LOC-1. 
[End of If structure] 
7. [Push right sublist onto stacks when it has 2 or more elements.] 
If LOC+1  END, then: 
TOP:=TOP+1, LOWER[TOP]:=LOC+1, 
UPPER[TOP]:=END. 
[End of If structure.] 
[End of Step 3 loop.] 
8. Exit.
QUICK(A,N,BEG,END,LOC) 
Here A is an array with N elements. Parameters BEG and END contain the boundary values of the sublist 
of A to which this procedure applies. LOC keeps track of the position of the first element A[BEG] of the 
sublist during the procedure. The local variables LEFT and RIGHT will contain the boundary values of 
the list of elements that have not been scanned. 
1. [Intialize] Set LEFT:=BEG, RIGHT:=END and LOC:=BEG. 
2. [Scan from right to left.] 
(a) Repeat while A[LOC]=A[RIGHT] and LOC!=RIGHT: 
RIGHT:=RIGHT-1. 
[End of loop] 
(b) If LOC=RRIIGGHHTT,, tthheenn:: RReettuurrnn.. 
(c) If A[LOC]A[RIGHT], then: 
(i) [Interchange A[LOC] and A[RIGHT]] 
TEMP:=A[LOC], A[LOC]:=A[RIGHT] 
A[RIGHT]:=TEMP 
(ii) Set LOC:=RIGHT 
(iii) Go to Step 3 
[End of If structure] 
3. [Scan from left to right] 
(a) Repeat while A[LEFT]=A[LOC] and LEFT!=LOC: 
LEFT:=LEFT+1 
[End of loop]
(b) If LOC=LEFT, then: Return 
(c) If A[LEFT]A[LOC], then 
(i) [Interchange A[LEFT] and A[LOC]] 
TEMP:=A[LOC],A[LOC]:=A[LEFT], 
A[LEFT]:=TEMP 
(ii) Set LOC:=LEFT 
(iii) Go to Step 2 
[End of If structure] 
Example: 44 33 11 55 77 90 40 6600 9999 2222 8888 6666 
22 33 11 55 77 90 40 60 99 44 88 66 
22 33 11 44 77 90 40 60 99 55 88 66 
22 33 11 40 77 90 44 60 99 55 88 66 
22 33 11 40 44 90 77 60 99 55 88 66 
22 33 11 40 44 90 77 60 99 55 88 66
Recursive Backtracking 
• Backtracking is a process where steps are taken towards the 
final solution and the details are recorded. If these steps do 
not lead to a solution some or all of them may have to be 
retraced and the relevant details discarded. 
• Trial and Error Process 
• Each time we make a recursive call, we will have to make a 
choice as to which decomposition to use. If we choose the 
wrong one, we will eventually run into a dead end and find 
ourselves in a state from which we are unable to solve the 
problem immediately and unable to decompose the problem 
any further; when this happens, we will have to backtrack to 
a choice point and try another alternative
The Famous Eight Queen Problem 
Link to Eight Queen Video
• Computationally expensive as there are 
4,426,165,368 (i.e., 64 choose 8) possible 
arrangements of eight queens on a 8×8 board 
• i.e 
64! / 8! (64-8)!
The 12 Unique Solutions with 8 queens
With 9 and 10 Queens
References for Eight Queen Problem 
• http://www.animatedrecursion.com/advanced/the_ 
eight_queens_problem.html 
• http://www.stanford.edu/class/cs106x/handouts/19- 
Recursive-BBaacckkttrraacckkiinngg..ppddff 
• http://en.wikipedia.org/wiki/Backtracking 
• http://en.wikipedia.org/wiki/Eight_queens_puzzle
Assignment 2 
• Write the program for Eight Queen Problem in C using 8X8 
matrix using recursion. 
Submission Date: March 2014
Class Assessment 
• Write the algorithm for Eight Queen Problem in Pseudocode.
Thank You

Dsoop (co 221) 1

  • 1.
    DSOOP (CO 221) B.Tech 4th Sem (ECE and ME)
  • 2.
    Recursion Def: Theidea of one function calling itself Example Problems: Factorial Fibonacci Series Towers of Hanoi
  • 3.
    Factorial using Recursion • #include<stdio.h> long factorial(int n) • { • long factorial(int); if (n == 0) • return 1; • int main() else • { return(n * factorial(n-1)); int num; } • long f; • • printf("Enter a number to ffiinndd ffaaccttoorriiaallnn""));; • scanf("%d", &num); • • if (num < 0) • printf("Negative numbers are not allowed.n"); • else • { • f = factorial(num); • printf("%d! = %ldn", num, f); • } • return 0; • }
  • 4.
    Fibonacci using Recursion • #include<stdio.h> int Fibonacci(int n) • { • int Fibonacci(int); if ( n == 0 ) » • main() return 0; • { else if ( n == 1 ) • int n, i = 0, c; return 1; • else • scanf("%d",&n); return ( Fibonacci(n-1) + Fibonacci(n-2) ); • printf("Fibonacci sseerriieessnn""));; }} • • for ( c = 1 ; c <= n ; c++ ) • { • printf("%dn", Fibonacci(i)); • i++; • } • • return 0; • }
  • 5.
    Towers of Hanoi A mathematical game or puzzle. Also known as Lucas Tower or Towers of Brahma. Components: 3 rods or pegs Number of disks of various sizes
  • 6.
    Origin Inventedby French Mathematician, Edouard Lucas in 1883 Indian Temple with 3 posts 64 golden disks 264-1 moves or seconds, one move per second, roughly 585 billion years i.e. 18,446,744,073,709,551,615 moves
  • 7.
    Rules for LucasTower • You can move only one disk at a time. • Each move consists of taking the upper disk from one of the rods and sliding it onto another rod, on top ooff tthhee ootthheerr ddiisskkss tthhaatt may already be present on that rod. • No disk may be placed on top of a smaller disk. • Video simulation-
  • 8.
    Computational Time orSolution n – number of disks Number of moves required to solve the puzzle f(n)= 2n - 1
  • 9.
    a) The initialstate; b) move n - 1 disks from A to C
  • 10.
    c) move onedisk from A to B; d) move n - 1 disks from C to B
  • 11.
  • 12.
    The Recursive Algorithm MoveTower (N, Beg, Aux, End) 1. If n=1, then; (a) Write: Beg - End (b) Return [EEnndd ooff IIff SSttrruuccttuurree]] 2. Move n-1 disks from peg/pole Beg to peg/pole Aux Call MoveTower(n-1,Beg,End,Aux) 3. Write Beg- End 4. Move n-1 disk from peg /pole Aux to peg/pole End Call MoveTower(n-1, Aux, Beg, End) 5. Return
  • 13.
    MoveTower(3,A,B,C) MoveTower(2,A,C,B) MoveTower(2,B,A,C) MoveTower(1,A,B,C) MoveTower(1,C,A,B) MoveTower(1,B,C,A) MoveTower(1,A,B,C) A - C A -B C - B A - C B - A B - C A - C A B C A B C A B C A B C Initial State (1) A - C (2) A - B (3) C - B A B C A B C A B C A B C (4) A - C (5) B - A (6) B - C (7) A - C
  • 14.
    MoveTower(3,A,B,C) MoveTower(2,A,C,B) MoveTower(2,B,A,C) MoveTower(1,A,B,C) MoveTower(1,C,A,B) MoveTower(1,B,C,A) MoveTower(1,A,B,C) A - C A -B C - B A - C B - A B - C A - C A B C A B C A B C A B C Initial State (1) A - C (2) A - B (3) C - B A B C A B C A B C A B C (4) A - C (5) B - A (6) B - C (7) A - C
  • 15.
    Recursion Disadvantage •Recursive algorithms have more overhead than similar iterative algorithms – Because of the repeated method calls (storing and removing data from call stack) – This may also cause a “stack overflow” when the call stack ggeettss ffuullll • It is often useful to derive a solution using recursion and implement it iteratively – Sometimes this can be quite challenging! (Especially, when computation continues after the recursive call - we often need to remember value of some local variable - stacks can be often used to store that information.)
  • 16.
    Recursion Disadvantage •Some recursive algorithms are inherently inefficient • An example of this is the recursive Fibonacci algorithm which repeats the same calculation again and again – Look at the number of times fib(2) is called • Even if the solution was determined using rreeccuurrssiioonn ssuucchh algorithms should be implemented iteratively • To make recursive algorithm efficient: – Generic method (used in AI): store all results in some data structure, and before making the recursive call, check whether the problem has been solved. – Make iterative version.
  • 17.
    Function Analysis forcall fib(5) 5 fib(5) 3 2 fib(4) fib(3) int fib(int n) if (n == 0 || n == 1) return n else return fib(n-1) + fib(n-2) fib(3) fib(2) fib(2) fib(1) fib(1) fib(0) fib(1) fib(0) fib(2) fib(1) fib(1) fib(0) 1 1 1 1 1 0 0 0 1 2 1 1
  • 18.
    Assignment 1 •Write the program for Tower of Hanoi in C++ using linked lists using recursion. Submission: Within FFeebbrruuaarryy 22001144
  • 19.
    References for Towersof Hanoi • Data Structures by Seymor Lipschutz • http://en.wikipedia.org/wiki/Tower_of_Hanoi
  • 20.
    Divide and ConquerAlgorithms Definition: For a problem P associated with a set S, if A is an algorithm which partitions S into smaller sets such that the solution of the problem P for S is reduced to the solution of P for one or more of the smaller sets. Then A is called a Divide and CCoonnqquueerr aallggoorriitthhmm. Algorithms: Quick Sort Algorithm Binary Search Algorithm
  • 21.
    (Quick Sort) Thisalgorithm sorts an array A with N elements. 1. [Initialize] TOP:=NULL 2. [Push boundary values of A onto stacks when A has 2 or more elements.] If N1, then :TOP:=TOP+1, LOWER[1]:=1,UPPER[1]:=N. 3. Repeat Steps 4 to 7 while TOP!=NULL. 3. [Pop sublist from stacks.] Set BEG:=LOWER[TOP], END:=UPPER[TOP], TOP:=TOP-1. 5. Call QUICK(A,N,BEG,END,LOC) 6. [Push left sublist onto stacks when it has 2 or more elements.] IIff BBEEGGLLOOCC-11,, tthheenn :: TOP:=TOP+1, LOWER[TOP]:=BEG, UPPER[TOP]=LOC-1. [End of If structure] 7. [Push right sublist onto stacks when it has 2 or more elements.] If LOC+1 END, then: TOP:=TOP+1, LOWER[TOP]:=LOC+1, UPPER[TOP]:=END. [End of If structure.] [End of Step 3 loop.] 8. Exit.
  • 22.
    QUICK(A,N,BEG,END,LOC) Here Ais an array with N elements. Parameters BEG and END contain the boundary values of the sublist of A to which this procedure applies. LOC keeps track of the position of the first element A[BEG] of the sublist during the procedure. The local variables LEFT and RIGHT will contain the boundary values of the list of elements that have not been scanned. 1. [Intialize] Set LEFT:=BEG, RIGHT:=END and LOC:=BEG. 2. [Scan from right to left.] (a) Repeat while A[LOC]=A[RIGHT] and LOC!=RIGHT: RIGHT:=RIGHT-1. [End of loop] (b) If LOC=RRIIGGHHTT,, tthheenn:: RReettuurrnn.. (c) If A[LOC]A[RIGHT], then: (i) [Interchange A[LOC] and A[RIGHT]] TEMP:=A[LOC], A[LOC]:=A[RIGHT] A[RIGHT]:=TEMP (ii) Set LOC:=RIGHT (iii) Go to Step 3 [End of If structure] 3. [Scan from left to right] (a) Repeat while A[LEFT]=A[LOC] and LEFT!=LOC: LEFT:=LEFT+1 [End of loop]
  • 23.
    (b) If LOC=LEFT,then: Return (c) If A[LEFT]A[LOC], then (i) [Interchange A[LEFT] and A[LOC]] TEMP:=A[LOC],A[LOC]:=A[LEFT], A[LEFT]:=TEMP (ii) Set LOC:=LEFT (iii) Go to Step 2 [End of If structure] Example: 44 33 11 55 77 90 40 6600 9999 2222 8888 6666 22 33 11 55 77 90 40 60 99 44 88 66 22 33 11 44 77 90 40 60 99 55 88 66 22 33 11 40 77 90 44 60 99 55 88 66 22 33 11 40 44 90 77 60 99 55 88 66 22 33 11 40 44 90 77 60 99 55 88 66
  • 24.
    Recursive Backtracking •Backtracking is a process where steps are taken towards the final solution and the details are recorded. If these steps do not lead to a solution some or all of them may have to be retraced and the relevant details discarded. • Trial and Error Process • Each time we make a recursive call, we will have to make a choice as to which decomposition to use. If we choose the wrong one, we will eventually run into a dead end and find ourselves in a state from which we are unable to solve the problem immediately and unable to decompose the problem any further; when this happens, we will have to backtrack to a choice point and try another alternative
  • 25.
    The Famous EightQueen Problem Link to Eight Queen Video
  • 26.
    • Computationally expensiveas there are 4,426,165,368 (i.e., 64 choose 8) possible arrangements of eight queens on a 8×8 board • i.e 64! / 8! (64-8)!
  • 27.
    The 12 UniqueSolutions with 8 queens
  • 29.
    With 9 and10 Queens
  • 30.
    References for EightQueen Problem • http://www.animatedrecursion.com/advanced/the_ eight_queens_problem.html • http://www.stanford.edu/class/cs106x/handouts/19- Recursive-BBaacckkttrraacckkiinngg..ppddff • http://en.wikipedia.org/wiki/Backtracking • http://en.wikipedia.org/wiki/Eight_queens_puzzle
  • 31.
    Assignment 2 •Write the program for Eight Queen Problem in C using 8X8 matrix using recursion. Submission Date: March 2014
  • 32.
    Class Assessment •Write the algorithm for Eight Queen Problem in Pseudocode.
  • 33.