0% found this document useful (0 votes)
6 views15 pages

T2 DS Recursion (MConverter - Eu)

The document provides an overview of recursion, including its definition, role of the stack, advantages and disadvantages, and types of recursion. It includes examples such as the Towers of Hanoi game and the Fibonacci series, demonstrating both direct and indirect recursion through C programming code. The document emphasizes the importance of base cases in recursive functions to prevent infinite loops and stack overflow.

Uploaded by

saichandnara2102
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views15 pages

T2 DS Recursion (MConverter - Eu)

The document provides an overview of recursion, including its definition, role of the stack, advantages and disadvantages, and types of recursion. It includes examples such as the Towers of Hanoi game and the Fibonacci series, demonstrating both direct and indirect recursion through C programming code. The document emphasizes the importance of base cases in recursive functions to prevent infinite loops and stack overflow.

Uploaded by

saichandnara2102
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 15

Data Structures

Recursion

Presidency University, Bengaluru


Contents

Recursion:
 Introduction & definition
 Role of stack in recursion
 Advantages & disadvantages
 Types of recursion
 Examples of recursion
 Towers of Hanoi game using recursion
 Fibonacci Series

Presidency University, Bengaluru


Introduction :

What is a Recursion
Definition:
Recursion is a process in which a function calls itself (directly or indirectly),
and the function is called as recursive function.
While writing a recursive function, we should take care of two things to avoid
infinite loop. They are:
• a) Base case: Base case tells when the recursion has to stop. It is also
known as stopping case or terminating condition.
• b) After every call of the recursive function, the control should come closer
to the base case.
Note : Without base case your function will never terminate and stack
overflow problem may arise(run out of memory to hold items in the stack.)
Note : Recursion is one way to decompose a task into smaller subtasks. A
recursive function is one that knows the answer to a specific case; in all other
cases, the function calls itself again
In simple words “Recursion is a process in which the problem is specified in
terms of itself”
Presidency University, Bengaluru
Role of the stack in Recursion:

When the recursive program is executed, the recursive function calls are not
evaluated immediately. They are placed on a stack until the base case/
terminating condition is encountered. After satisfying the terminating
condition the function calls are exe8cuted in reverse order, because the data
structure stack is involved.

 Whenever a function is called, its activation record will be maintained


inside of the stack.
 Activation record consists of local variables of the function, parameters of
the function and return address of the caller.
 These activation records of all the functions used in the program (even for
main() function also) stored / pushed into the stack.
 When control is exited from a particular function, then corresponding
activation record is popped out / removed from the stack.

Presidency University, Bengaluru


Advantages & disadvantages of Recursion

Advantages :
• Recursion reduces the length of the code
• Using recursion, certain problems can be solved quite easily. Examples of
such problems are Towers of Hanoi (TOH), Inorder/Preorder/Postorder
Tree Traversals, DFS of Graph, etc.
• Through Recursion one can Solve problems in easy way while its iterative
solution is very big and complex.

Disadvantages :
• Recursive solution is always logical and it is very difficult to trace.(debug
and understand).
• Recursion uses more memory, because the function has to add to the stack
with each recursive call and keep the values there until the call is finished.
• Recursion uses more processor time than iteration.

Presidency University, Bengaluru


Types of Recursion : Direct & Indirect Recursion

Recursion can be classified into two types as:


1. Direct recursion
A function calls itself is known as direct recursion.
Example : Factorial of a given number

2. Indirect recursion
If the function f1 calls another function f2 and f2 calls f1 then it is indirect
recursion (or mutual recursion).
Example : add 1 to odd number, subtract 1 from even number program

Presidency University, Bengaluru


// demo of direct recursion
// program to find factorial of a number using recursion
#include<stdio.h> // 1!= answer is 1
int factorial(int n) // 2! = 2 x (2-1)! => 2 x 1!
{ // 3! = 3 x 2! = 3 x 2 x 1!
if(n==1) // base case // some mem locations STACK
return(1);
else
return(n*factorial(n-1)); ///5*24-> 4*6-3*22*11
}
void main()
{
int n,result;
scanf("%d",&n);
result=factorial(n);//120
printf("%d factorial is %d \n",n,result);
}
Presidency University, Bengaluru
1 2 3 4 5 6 7 8 9 10
1+1 2-1 3+1 4-1 5+1 6-1
// demo of indirect recursion
/* WAP to print numbers from 1 to 10 in such a way that when number is odd,
add 1 and when number is even, subtract 1.
Output : 2 1 4 3 6 5 8 7 10 9 2 1 4 3 6 5 8 7 10 9

odd () function handles odd numbers, when odd number is encountered it adds
1 and print that number on the screen.
Even() function handles even numbers, when even number is encountered it
subtracts 1 and print that number on the screen.*/
#include<stdio.h>
void even();
void odd(); // prototypes
int n=1; // global variable
void main()
{
odd();
}

Presidency University, Bengaluru


void odd() //// 2 1 4 3 6 5 8 7 10 9
{
if(n<=10)
{
printf("%d\t",n+1); //2 4 6 8 10
n++; // 2 4 6 8 10
even();
}
return;
}
void even()
{
if(n<=10)
{
printf("%d\t",n-1); // 1 3 5 7 9
n++; // 3 5 7 9 11
odd();
}
return;
}
Presidency University, Bengaluru
Fibonacci numbers / series

 In fibonacci series, current number/ term is the sum of previous two numbers,
for example 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55 etc.
 The first two numbers of fibonacci series are 0 and 1.
// fibonacci series without recursion// t1 t2 t3
#include<stdio.h> // 0 1 1
void main() // 1 1 2
{ // 1 2 3
int t1=0,t2=1,t3,term,n; // 2 3 5
printf("how many terms \n");
scanf("%d",&n); //10
printf("%d\t%d\t",t1,t2); //printing first two terms, 0 and 1
for(term=3;term<=n;term++)// we have to print from 3rd term
{
t3=t1+t2; // current term is sum of two previous terms
printf(" %d\t",t3);
t1=t2;
t2=t3;
} return; }
Presidency University, Bengaluru
Fibonacci numbers /series using recursion

#include<stdio.h>
int fibonacci(int n)
{
if ( n == 0 )
return 0;
else if ( n == 1 )
return 1;
else
return (fibonacci(n-1) + fibonacci(n-2) );
}
void main()
{ int n, i = 0, term;
printf("how many terms \n");
scanf("%d",&n);
printf("fibonacci series\n");
for (term=1;term<= n ;term++ ) // 10 times i=0 1 2 3
{
printf("%d\t", fibonacci(i)); // 0 1 1
i++;
} return ; }
Presidency University, Bengaluru
Towers of Hanoi

Towers of Hanoi is a well-known children’s game, played with three poles (known as
left, center and right poles or towers) and number of different sized disks. (that is
disks with different radii).
Initially, the disks are stacked on the left most pole in the order of decreasing order,
ie., the largest disk on the bottom and smallest disk on the top. (see the figure)

Presidency University, Bengaluru


How to play Towers of Hanoi

The objective of the game is to transfer the disks from the leftmost pole to the
rightmost pole.

The following points to be remembered while playing the game:


 In each move larger disk should not be placed on the top of a smaller disk.
 Only one disk may be moved at a time, and each disk must always be placed
around on of the poles.

The problem can be solved in the following recursive manner.


 Move top n-1 disks from left pole to center pole
 Move the nth disk (largest disk) to the right pole.
 Move n-1 disks on the center pole to right pole.

Presidency University, Bengaluru


Implementation of Towers of Hanoi using C

// demo of towers of hanoi game - using recursion


#include<stdio.h>
void transfer(int n, char from, char to, char temp)
/* here n = number of disks, from = origin, to = destination, temp = temporary
storage */
{
if(n>0)
{
/* move n-1 disks from origin to temporary pole */
transfer(n-1,from,temp,to);
/* move n th disk from origin to destination */
printf("move disk %d from %c to %c pole\n",n,from,to);
/* move n-1 disks from temporary to destination pole */
transfer(n-1,temp,to,from);
}
return;
}

Presidency University, Bengaluru


Implementation of Towers of Hanoi using C

void main()
{
int n;
printf("how many disks \n");
scanf("%d",&n);

/* The below function call actual parameters are specified as character


constants.
The function call also specifies the transfer all n disks from the leftmost
pole(origin) to rightmost pole (destination), using the center pole for
temporary storage */

transfer( n,'L','R','C'); // function call


return;
}

Presidency University, Bengaluru

You might also like