0% found this document useful (0 votes)
60 views

DSA Recursion

Recursion is defined as defining anything in terms of itself. There are two key properties of recursion: 1) there must be a base case for which the procedure does not call itself, and 2) each recursive call must get closer to the base case. Recursion can be used to solve problems by breaking them down into smaller sub-problems until reaching the base case. Examples of problems solved recursively include calculating factorials, Fibonacci numbers, greatest common divisors, and the Tower of Hanoi puzzle.

Uploaded by

Riyaz Shrestha
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
60 views

DSA Recursion

Recursion is defined as defining anything in terms of itself. There are two key properties of recursion: 1) there must be a base case for which the procedure does not call itself, and 2) each recursive call must get closer to the base case. Recursion can be used to solve problems by breaking them down into smaller sub-problems until reaching the base case. Examples of problems solved recursively include calculating factorials, Fibonacci numbers, greatest common divisors, and the Tower of Hanoi puzzle.

Uploaded by

Riyaz Shrestha
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 21

Recursion

Kashiram Pokharel
Recursion:
• Recursion is defined as defining anything in terms of itself. Syntax:-
Recursion is used to solve problems involving iteration s in Main()
{
reverse order. ----------
Function();
• Recursive functions:-
-----------
• A function calls itself repeatedly. }
Function()
• Recursive program will not continue infinitely. A recursive {
procedure must have the following two properties. Function();
• There must be the certain criteria, called base criteria for which
}
the procedures does not call itself.
• Each time the procedure does call itself, it must be closer to base
criteria.
Comparison between recursion and iteration
RECURSION ITERATIONS
Recursive function – is a function that is Iterative Instructions –are loop based
partially defined by itself repetitions of a process
Recursion Uses selection structure Iteration uses repetition structure
Infinite recursion occurs if the recursion An infinite loop occurs with iteration
step does not reduce the problem in a if the loop-condition test never
manner that converges on some becomes false
condition.(base case)
Recursion terminates when a base case is Iteration terminates when the loop-
recognized condition fails
Recursion is usually slower then iteration Iteration does not use stack so it's
due to overhead of maintaining stack faster than recursion
Recursion uses more memory than Iteration consume less memory
iteration
Infinite recursion can crash the system infinite looping uses CPU
cycles repeatedly
Recursion makes code smaller Iteration makes code longer
Type of recursion
• Direct recursion • a function is called by itself but indirectly, such that two
functions called one another mutually is called indirect
• Indirect Recursion recursion.
A function which calls itself from within its body is called direct Int abc()
recursion.
{
Int abc()
……..
{
Xyz()
…..
……..
…….
}
Abc()
Int xyz()
……….
{
}
……..
Fig direct recursion
Abc()
…….
}
Fig indirect recursion
• Represented graphically it looks like:
Type of recursion( based on number of recursive call)
• Recursion can further categorized into the following types
• Linear recursion: The recursion which begins by testing for the set of base
cases in which every possible chain of recursive call must eventually reach
a base case and handling of each base case should not use recursion is
called linear recursion . For example factorial of number using recursion.

• Binary recursion: It is a recursion in which there are two recursive calls for
each non base case. For example recursive definition for finding Fibonacci
sequence.

• Multiple recursion. In multiple recursion, we make not just one or two but
many recursive calls.
• Linear recursion (these two types of linear recursion are equally powerful;
if not explicitly told so, you can use either one)
• Embedded recursion
• Used when processing a linear list of elements, or by making a problem one unit smaller.
• When we get to the base case, we still have post-processing work to do, since we haven't
been keeping track of things all along
• Tail recursion
• Used when processing a linear list of elements, or by making a problem one unit smaller.
• When we get to the base case, we're done, since we've been keeping track of things all along
• You usually need helper functions to keep track of your running total answers when you write
tail recursive programs
• A tail recursion is a recursive function where the function calls itself at the end ("tail") of the
function in which no computation is done after the return of recursive call. Many compilers
optimize to change a recursive call to a tail recursive or an iterative call.
• Non-linear recursion
• car-cdr recursion
• Used when processing a deep list, or by making the problem multiple units smaller at
once.
• Typically written by starting with embedded recursion and adding a single case to
the cond.
• Nested recursion
• Used when processing a deep list, or in our recursive procedure we need to do
something recursive.
• We call recursive functions within recursive functions, very powerful.
Need for recursion:-
• There must be a terminating condition for problem which you want to
solve with recursion. This condition is called the base criteria for that
problem. There must be an if condition in the recursion routing, this if
clause specifies the terminating condition for the recursion.
• Reversal in the order of execution is the characteristic of every recursion.
Problem.
• Every time a new recursive calls is made, a new memory space is allocate
to each automatic variables used by the recursive routine.
• The duplicated values of the local variables of a recursive call are pushed
on to the stack with it’s respective call & all these value are available to the
respective function when it is popped off from the stack.
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.
• Doesn’t offer any concrete advantage over non recursive functions.
• If proper precautions are not taken, recursion may result non terminating
iterations.
Output process:-
Find the factorial of any Factorial(5)=
input number. 5*Factorial(4)=
int find_factorial(int); 5*(4*Factorial(3))=
int main() 5*(4*(3*Factorial(2)))=
{ 5*(4*(3*(2*Factorial(1))))=
int num, fact; 5*(4*(3*(2*(1*Factorial(0)))))=
printf("\nEnter any integer number:"); 5*(4*(3*(2*(1*1))))=
scanf("%d",&num); 5*(4*(3*(2*1)))=
fact =find_factorial(num); 5*(4*(3*2))=
printf("\nfactorial of %d is: %d",num, fact); 5*(4*6)=
return 0; 5*24=
} 120
int find_factorial(int n) For n=3, recursion tree becomes
{
if(n==0)
return(1);
return(n*find_factorial(n-1));
}
Fibonacci series using recursion
#include<stdio.h> • The recursion tree of Fibonacci series is
int Fibonacci(int);
int main()
{
int n, i = 0, c;
scanf("%d",&n);
printf("Fibonacci series\n");
for ( c = 1 ; c <= n ; c++ )
{
printf("%d\n", Fibonacci(i));
i++;
}
return 0;
}
int Fibonacci(int n)
{
if ( n == 0 )
return 0;
else if ( n == 1 )
return 1;
else
return ( Fibonacci(n-1) + Fibonacci(n-2) );
}
GCD using recursion
#include <stdio.h>
int hcf(int n1, int n2);
int main() {
int n1, n2;
printf("Enter two positive integers: ");
scanf("%d %d", &n1, &n2);
printf("G.C.D of %d and %d is %d.", n1, n2, hcf(n1, n2));
return 0;
}
int hcf(int n1, int n2)
{
if (n2 != 0)
return hcf(n2, n1 % n2);
else
return n1;
}
Tower of Hanoi (TOH):-
• It is a game problem. In this case the disk is moved from one pillar to another
pillar with the use of temporary pillar.
Tower of Hanoi problem:
Initial state:
• There are three poles named as origin, intermediate and destination.
• n number of different-sized disks having hole at the center is stacked around the origin pole
in decreasing order.
• The disks are numbered as 1, 2, 3, 4, ……………….,n.
• Objective:
• Transfer all disks from origin pole to destination pole using intermediate pole for temporary
storage.
• Conditions:
• Move only one disk at a time.
• Each disk must always be placed around one of the pole.
• Never place larger disk on top of smaller disk.
Algorithm: - To move a tower of n disks from
source to dest (where n is positive integer):
• If n ==1: Program:
#include<stdio.h>
• Move a single disk from source to dest. void TOH(int n,char x,char y,char z) {
• If n > 1: if(n>0) {
TOH(n-1,x,z,y);
1. Let temp be the remaining pole printf("\n%c to %c",x,z);
other than source and dest. TOH(n-1,y,x,z);
2. Move a tower of (n – 1) disks form }
}
source to temp. int main()
3. Move a single disk from source to {
dest. int n;
printf("enter how many disk");
4. Move a tower of (n – 1) disks form scanf("%d",&n);
temp to dest. TOH(n,'S','T','D');
}
• Terminate.
Application of Recursion:
• To solve game:
• Bubble shooter game
• Chess game
• Windows paint application
• while Filling the colour in a particular area of the drawing/Model. It uses the
concept of flood fill while colouring a particular area of the drawing.
• Sorting Algorithms
• Most of the sorting algorithms uses the concept of recursion to sort the data
according to the given condition. Many of the Sorting algorithms like Quick
sort, Merge sort, etc
• Tree Data Structure:
• ‘Tree’ doesn’t exist without recursion. We can solve that in an iterative way
also but that will be a very tough task.
Search tree:
• Search in AI is the process of navigating from a starting state to a goal
state by transitioning through intermediate states. which is carried out by
constructing a search tree about the problem.
• A tree representation of search problem is called Search tree. The root of
the search tree is the root node which is corresponding to the initial state.
• Search tree may list all possible paths , eliminating cycles from the path
and we would get the complete search tree from a state space graph.
• A search tree is a data structure containing a root node, from where the
search starts i.e initial state, Every node may have 0 or more children which
represent the possible path to traverse from current node.
Search tree:
Thank You. .

You might also like