Title: More on Recursion
1More on Recursion
2A recursive max function
Int larger (int x, int y) if ( x gt y )
return x return y int max ( int
a, int n) if (n 1) return a0
return larger ( a0, max ( a1, n-1))
main() int a100, n ..
greatest max ( a, n) ..
3 Relook at the Fibonacci solution fib(n) 1 if
n 0 or 1 fib(n 2) fib(n
1) otherwise
int fib (int n) if (n0 n1) return
1 return fib(n-2) fib(n-1)
fib (5)
fib (3)
fib (4)
fib (2)
fib (1)
fib (2)
fib (3)
fib (1)
fib (2)
fib (0)
fib (1)
fib (1)
fib (0)
This is not efficient !! Same sub-problem solved
many times.
fib (1)
fib (0)
4Tower of Hanoi
A
B
C
5Tower of Hanoi
A
B
C
6Tower of Hanoi
A
B
C
7Tower of Hanoi
A
B
C
8Towers of Hanoi function
void towers (int n, char from, char to, char aux)
/ Base Condition / if (n1)
printf (Disk 1 c ? c \n, from, to)
return / Recursive Condition /
. .
.
9Towers of Hanoi function
void towers (int n, char from, char to, char aux)
/ Base Condition / if (n1)
printf (Disk 1 c ? c \n, from, to)
return / Recursive Condition /
towers (n-1, from, aux, to)
. .
10Towers of Hanoi function
void towers (int n, char from, char to, char aux)
/ Base Condition / if (n1)
printf (Disk 1 c ? c \n, from, to)
return / Recursive Condition /
towers (n-1, from, aux, to)
printf (Disk d c ? c\n, n, from, to)
.
11Towers of Hanoi function
void towers (int n, char from, char to, char aux)
/ Base Condition / if (n1)
printf (Disk 1 c ? c \n, from, to)
return / Recursive Condition /
towers (n-1, from, aux, to)
printf (Disk d c ? c\n, n, from, to)
towers (n-1, aux, to, from)
12TOH runs
void towers(int n, char from, char to, char
aux) if (n1) printf ("Disk 1 c -gt
c \n", from, to) return towers
(n-1, from, aux, to) printf ("Disk d c
-gt c\n", n, from, to) towers (n-1, aux, to,
from) main() int n scanf("d", n)
towers(n,'A',C',B')
scd ./a.out 2 Disk 1 A -gt B Disk 2 A -gt
C Disk 1 B -gt C scd ./a.out 3 Disk 1 A -gt
C Disk 2 A -gt B Disk 1 C -gt B Disk 3 A -gt
C Disk 1 B -gt A Disk 2 B -gt C Disk 1 A -gt C
13More TOH runs
scd ./a.out 4 Disk 1 A -gt B Disk 2 A -gt
C Disk 1 B -gt C Disk 3 A -gt B Disk 1 C -gt
A Disk 2 C -gt B Disk 1 A -gt B Disk 4 A -gt
C Disk 1 B -gt C Disk 2 B -gt A Disk 1 C -gt
A Disk 3 B -gt C Disk 1 A -gt B Disk 2 A -gt
C Disk 1 B -gt C
void towers(int n, char from, char to, char
aux) if (n1) printf ("Disk 1 c -gt
c \n", from, to) return towers
(n-1, from, aux, to) printf ("Disk d c
-gt c\n", n, from, to) towers (n-1, aux, to,
from) main() int n scanf("d", n)
towers(n,'A',C',B')