Recursion
A function is recursive if a statement in the body of the function calls
itself.
Recursion is the process of defining something in terms of itself.
For a computer language to be recursive, a function must be able to
call itself.
Recursion: factorial
#include <stdio.h> int factorial (int n)
int factorial (int); {
main() int result;
{ if (n == 0)
int num, fact; return (1);
printf (“Enter a positive else
integer value: "); result = n * factorial (n-1);
scanf (“%d”, &num); return (result);
fact = factorial (num); }
printf ("\n Factorial of %d =
%5d\n", num, fact);
}
Non recursive-Iteration
factorial (int n)
{
int i, result = 1;
if (n == 0)
return (result);
else
{
for (i=1; i<=n; i++)
result = result * i;
}
return (result);
}
Tower of Hanoi
• There are three towers
• n disks, with decreasing sizes, placed on the first
tower
• You need to move all of the disks from the first
tower to the last tower
• Larger disks can not be placed on top of smaller
disks
• The third tower can be used to temporarily hold
disks
Recursive Solution
Recursive Solution
Recursive Solution
Recursive Solution
Tower of Hanoi
Tower of Hanoi
Tower of Hanoi
Tower of Hanoi
Tower of Hanoi
Tower of Hanoi
Tower of Hanoi
Tower of Hanoi
Tower of Hanoi
(0,0,0)
Tower of Hanoi
(0,0,1)
Tower of Hanoi
(0,1,1)
Tower of Hanoi
(0,1,0)
Tower of Hanoi
(1,1,0)
Tower of Hanoi
(1,1,1)
Tower of Hanoi
(1,0,1)
Tower of Hanoi
(1,0,0)
Tower of Hanoi
Three pegs, one with n disks of decreasing diameter; two
other pegs are empty
Task: move all disks to the third peg under the following
constraints
Can move only the topmost disk from one peg to another in one
step
Cannot place a smaller disk below a larger one