Recursion
Recursion
Ramesh Saud 1
Types of Recursive function in C
• When a function calls itself directly or indirectly, it is
called recursive function.
• Two types:
(i) Direct Recursion (ii) Indirect Recursion
• E.g.
void main()
{
printf(“This is direct recursion. Goes infinite\n");
main();
}
Ramesh Saud 2
Contd…
• E.g.
void printline();
void main()
{
printf(“ This is not direct recursion.\n");
printline();
}
void printline()
{
printf("Indirect Recursion. Goes Infinite\n");
main();
}
Ramesh Saud 3
Problem solving with Recursion
• To solve a problem using recursive method, two
conditions must be satisfied:
1) Problem should be written or defined in terms of its
previous result.
2) Problem statement must include a terminating
condition, otherwise the function will never terminate.
This means that there must be an if statement
somewhere in the recursive function to force the
function to return without the recursive call being
executed.
Ramesh Saud 4
Recursion versus Iteration
1. A function is called from the definition of the same function to do repeated task.
2. Recursion is a top-down approach to problem solving: it divides the problem into
pieces.
E.g. Computing factorial of a number:
long int factorial(int n)
{
if(n==0) return 1;
else
return (n*factorial(n-1));
}
3. Problem to be solved is defined in terms of its previous result to solve a problem
using recursion.
4. In recursion, a function calls to itself until some condition is satisfied.
5. All problems cannot be solved using recursion.
6. Recursion utilizes stack.
Ramesh Saud 5
Iteration
1. Loops are used to perform repeated task.
2. Iteration is a bottom-up approach: it begins from what is known and
from this it constructs the solution step-by-step.
E.g. Computing factorial of a number:
int fact=1;
for(i=1;i<=n;i++)
{
fact=fact*i;
}
3. It is not necessary to define a problem in terms of its previous result
to solve using iteration. For e.g. “Display your name 1000 times”
4. In iteration, a function does not call to itself.
5. All problems can be solvedRameshusingSaud
iteration. 6
6. Iteration does not utilize stack.
Use of Stack in Recursion
• Recursion uses stack to keep the successive generations of local
variables and parameters of the function in its corresponding calls.
• This stack is maintained by the C system and is invisible to the user
(programmer).
• Each time a recursive function is entered, a new allocation of its
variables is pushed on top of the stack.
• Any reference to a local variable or parameter is through the current
top of the stack.
• When the function returns, the stack is popped, the top allocation is
freed, and the previous allocation becomes the current stack top to be
used for referencing local variables.
• Each time a recursive function returns, it returns to the point
immediately following the point from which it was called.
Ramesh Saud 7
Implementation of Factorial
long int factorial(int n)
{
if(n==0)
return 1;
else
return (n*factorial(n-1));
}
void main()
{
int number;
long int x;
clrscr();
printf("Enter a number whose factorial is needed:\t");
scanf("%d", &number);
x=factorial(number);
printf("\n The factorial is:%ld", x);
getch();
}
Ramesh Saud 8
While calculating the factorial
of n=5, the else part gets
executed and the value
5*factorial(4) is pushed onto the
stack. Then the factorial
function gets called again
recursively with n=4 and
4*factorial(3) is executed and is
pushed onto the stack. This
process goes on like this. When
factorial(1) becomes
1*factorial(0) the factorial
function is called again with
n=0. When n becomes 0, the
function returns 1 and after this
the recursive function starts to
return in a last-in, first-out
manner. The recursive function
returns successive values to the
point from which it was called
in the stack so that the final
value returned is 5*24=120.
Ramesh Saud 9
• Determine what the following recursive C
function computes. Write an iterative function to
accomplish the same purpose.
int func(int n)
{
if(n==0)
return (0);
return (n + func(n-1));
} /* end func */
Ramesh Saud 10
• The recursive function computes the sum of integers from 0 to
n where n is the input to the function.
• For calculating the sum of integers from 0 to n (with say n=5),
the recursive function computes as:
– With n=5, the else part gets executed and the value 5+func(4) is
pushed onto the recursive stack. Then the func function is
called again recursively with n=4 and 4+func(3) is executed
and is pushed onto the stack. This process goes on like this.
When func(1) becomes 1+func(0), the func function is called
again with n=0. When n becomes 0, the func function returns 0
and after this the recursive function starts to return in a last-
in, first-out manner. The recursive function returns successive
values to the point from which it was called in the stack so that
the final value returned is 5+10=15.
Ramesh Saud 11
Iterative
Function
int func(int n)
{
int sum=0;
int i;
for(i=0;i<=n;i
++)
sum =
sum+i;
Ramesh Saud return sum;12
Implementation of Multiplication of
Natural Numbers
int mult(int a, int b)
{
if(b==0)
return 0;
else
return (a+mult(a,--b));
}
void main()
{
int m, n;
int x;
clrscr();
printf("Enter two numbers you want to multiply:");
scanf("%d %d", &m, &n);
x=mult(m, n);
printf("%d*%d=%d", m, n, x);
getch();
}
Ramesh Saud 13
The “Towers of Hanoi” Problem
• There are 3 pegs A, B and C.
• Five disks (say) of different diameters are placed on peg A so that a larger
disk is always below a smaller disk.
• The aim is to move the five disks to peg C, using peg B as auxiliary.
• Only the top disk on any peg may be moved to any other peg, and a larger
disk may never rest on a smaller one.
Ramesh Saud 14
Basic Idea
• Let us consider the general case of n disks.
• If we can develop a solution to move n-1 disks,
then we can formulate a recursive solution to move
all n disks.
– In the specific case of 5 disks, suppose that we can
move 4 disks from peg A to peg C, using peg B as
auxiliary.
– This implies that we can easily move the 4 disks to peg
B also (by using peg C as auxiliary).
– Now we can easily move the largest disk from peg A to
peg C, and finally again apply the solution for 4 disks to
move the 4 disks from peg B to peg C, using the now
empty peg A as an auxiliary.
Ramesh Saud 15
Algorithm: Recursive Solution
• To move n disks from peg A to peg C, using
peg B as auxiliary:
1. If n==1, move the single disk from A to C and
stop.
2. Move the top n-1 disks from A to B, using C as
auxiliary.
3. Move the remaining disk from A to C.
4. Move the n-1 disks from B to C, using A as
auxiliary.
Ramesh Saud 16
Implementation of “Towers of Hanoi”
void transfer(int, char, char, char);
void main()
{ from : the
int n; peg from which
clrscr(); we are
printf("\n Input number of disks in peg A:"); removing disks
scanf("%d", &n);
transfer(n, 'A', 'C', 'B'); to : the peg to
getch(); which we will
}
void transfer(int n, char from, char to, char aux)
take the disks
{ aux: the
if(n==1) auxiliary peg
{
printf("\n Move disk %d from peg %c to peg %c", n, from, to);
return;
}
transfer(n-1,from,aux,to);
printf("\n Move disk %d from peg %c to peg %c", n, from, to);
transfer(n-1,aux,to,from);
}
Ramesh Saud 17
• Move disk 1 from peg A to peg C
2 2
1 1 1 1
•Draw the largest disk node with the largest disk number (disk number starts from 1,
with 1 being the smallest disk number) and put it directly to the destination (A->C).
•Draw its two children with the second largest node number i.e. 2.
•Now A->C can be accomplished only through A->B and B->C, so put A->B as left
child and B->C as right child.
•Again draw two children of second largest node i.e. 2 and think how we can generate
A->B and B->C………………………………..Completed
•Finally perform inorder traversal (left-root-right) of the tree to obtain the appropriate
sequence of steps to solve “Tower of Hanoi”.
•Note: On left side, we always have A and on right side, we always have C.
Ramesh Saud 18