6 Recursion
6 Recursion
Recursion
Recursion
Principle of Recursion
Comparison between Recursion and Iteration
Tail Recursion
Factorial
Fibonacci Sequence
GCD,Tower of Hanoi(TOH)
Applications and Efficiency of Recursion
Recursion
Advantages of Recursion:
➢ The code may be much easier to write.
➢ To solve some problems which are naturally recursive such as
tower of Hanoi.
Disadvantages of Recursion:
➢ Recursive functions are generally slower than non recursive
functions.
➢ May require a lot of memory to hold intermediate results on the
system stack.
➢ It is difficult to think recursively so one must be very careful
when writing recursive functions.
Recursion vs Iteration
Property Recursion Iteration
A set of instructions
Definition Function calls itself.
repeatedly executed.
Recursion are mainly of two types depending on whether a function calls itself from
within itself or more than one function call one another mutually. The first one is
called direct recursion and another one is called indirect recursion.
Direct Recursion: These can be further categorized into four types:
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. After that call the
recursive function performs nothing. The function has to process or perform any
operation at the time of calling and it does nothing at returning time.
Tail Recursion
A special form of recursion where the last operation of a function is a recursive call.
The recursion may be optimized away by executing the call in the current stack frame
and returning its result rather than creating a new stack frame.
The tail recursive functions considered better than non tail recursive functions as tail-
recursion can be optimized by compiler. Compilers usually execute recursive
procedures by using a stack. This stack consists of all the pertinent information,
including the parameter values, for each recursive call.
When a procedure is called, its information is pushed onto a stack, and when the
function terminates the information is popped out of the stack. Thus for the non tail-
recursive functions, the stack depth (maximum amount of stack space used at any
time during compilation) is more.
The idea used by compilers to optimize tail-recursive functions is simple, since the
recursive call is the last statement, there is nothing left to do in the current function,
so saving the current function's stack frame is of no use.
Tail Recursion
Example:
#include <stdio.h>
void fun(int n)
{
if (n > 0) {
printf("%d ", n);
fun(n - 1);
}
}
int main()
{
int x = 3;
fun(x);
return 0;
}
Head 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. There’s
no statement, no operation before the call. The function doesn’t have to
process or perform any operation at the time of calling and all operations are
done at returning time.
Example:
Head Recursion
#include <stdio.h>
void fun(int n)
{
if (n > 0) {
fun(n - 1);
printf("%d ", n);
}
}
int main()
{
int x = 3;
fun(x);
return 0;
}
Tree and Linear Recursion
Tree Recursion: To understand Tree Recursion let’s first understand Linear
Recursion.
If a recursive function calling itself for one time then it’s known as Linear
Recursion.
Otherwise if a recursive function calling itself for more than one time then it’s
known as Tree Recursion.
Example:
Tree Recursion
#include <stdio.h>
void fun(int n)
{
if (n > 0) {
printf("%d ", n);
fun(n - 1);
fun(n - 1);
}
}
int main()
{
fun(3);
return 0;
}
Indirect Recursion
Indirect Recursion: In this recursion, there may be more than one functions
and they are calling one another in a circular manner.
From the above diagram fun(A) is calling for fun(B), fun(B) is calling for
fun(C) and fun(C) is calling for fun(A) and thus it makes a cycle.
Indirect Recursion
Example: void funB(int n)
#include <stdio.h> {
void funB(int n); if (n > 1) {
void funA(int n) printf("%d ", n);
{ funA(n / 2);
if (n > 0) { }
printf("%d ", n); }
funB(n - 1); int main()
} {
} funA(20);
return 0;
}
Recursion Example
Factorial of a number:
Factorial of a non-negative integer is the multiplication of all positive integers smaller than or
equal to n. For example factorial of 6 is 6*5*4*3*2*1 which is 720.
A factorial is represented by a number and a ” ! ” mark at the end. It is widely used in
permutations and combinations to calculate the total possible outcomes. A French
mathematician Christian Kramp firstly used the exclamation.
#include <stdio.h>
unsigned int factorial(unsigned int n)
{
if (n == 0)
return 1;
return n * factorial(n - 1);
}
int main()
{
int num = 5;
printf("Factorial of %d is %d", num, factorial(num));
return 0;
}
Recursion Example
GCD of numbers:
Algorithm
Refer an algorithm given below to find the greatest common divisor (GCD)
for the given two numbers by using the recursive function.
Step 1 − Define the recursive function.
Step 2 − Read the two integers a and b.
Step 3 − Call recursive function.
a. if i>j
b. then return the function with parameters i,j
c. if i==0
d. then return j
e. else return the function with parameters i,j%i
Recursion Example
GCD of numbers:
#include<stdio.h>
#include<math.h>
unsigned int GCD(unsigned i, unsigned j);
int main(){
int a,b;
printf("Enter the two integers: \n");
scanf("%d%d",&a,&b);
printf("GCD of %d and %d is %d\n",a,b,GCD(a,b));
return 0;
}
unsigned int GCD(unsigned i, unsigned j){
if(j>i)
return GCD(j,i);
if(j==0)
return i;
else
return GCD(j,i%j);
}
Fibonacci numbers
The Fibonacci numbers are the }
numbers in the following integer
sequence.
int main()
0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89,
144, …….. {
In mathematical terms, the sequence int n;
Fn of Fibonacci numbers is defined by printf("enter no of terms:");
the recurrence relation
scanf("%d",&n);
Fn = Fn-1 + Fn-2
for(int i=0;i<n;i++)
with seed values F0 = 0 and F1 = 1.
printf("%d ", fib(i));
#include <stdio.h>
int fib(int n)
return 0;
{
}
if (n <= 1)
return n;
return fib(n - 1) + fib(n - 2);
Tower of Hanoi
Tower of Hanoi is a mathematical puzzle where we have three rods and n
disks. The objective of the puzzle is to move the entire stack to another rod,
obeying the following simple 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 Algorithm
To write an algorithm for Tower of Hanoi, first we need to learn how to solve
this problem with lesser amount of disks, say → 1 or 2. We mark three towers
with name, source, destination and aux (only to help moving the disks). If we
have only one disk, then it can easily be moved from source to destination peg.
If we have 2 disks:
First, we move the smaller (top) disk to aux peg.
Then, we move the larger (bottom) disk to destination peg.
And finally, we move the smaller disk from aux to destination peg.
Our ultimate aim is to move disk n from source to destination and then put all
other (n-1) disks onto it. We can imagine to apply the same in a recursive way
for all given set of disks.
The steps to follow are :
Step 1 − Move n-1 disks from source to aux.
Step 2 − Move nth disk from source to dest.
Step 3 − Move n-1 disks from aux to dest.
Tower of Hanoi Algorithm
START
Procedure Hanoi(disk, source, dest, aux)
IF disk == 1, THEN
move disk from source to dest
ELSE
Hanoi(disk - 1, source, aux, dest) // Step 1
move disk from source to dest // Step 2
Hanoi(disk - 1, aux, dest, source) // Step 3
END IF
END Procedure
STOP
Tower of Hanoi Algorithm
#include <stdio.h> // Base Condition if no of disks are
if (num == 1)
void towers(int, char, char, char); {
printf("\n Move disk 1 from peg %c
int main() to peg %c", frompeg, topeg);
{ return;
int num; }