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

Unit - 4 Recursion

The document provides an overview of recursion, explaining its definition, types (direct and indirect), and basic requirements including base and general cases. It discusses the advantages and disadvantages of recursion compared to iteration, along with practical examples such as calculating factorials, Fibonacci series, and solving the Tower of Hanoi problem using recursive functions. Additionally, it covers the concept of search trees and highlights the benefits of recursion in simplifying code and solving naturally recursive problems.

Uploaded by

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

Unit - 4 Recursion

The document provides an overview of recursion, explaining its definition, types (direct and indirect), and basic requirements including base and general cases. It discusses the advantages and disadvantages of recursion compared to iteration, along with practical examples such as calculating factorials, Fibonacci series, and solving the Tower of Hanoi problem using recursive functions. Additionally, it covers the concept of search trees and highlights the benefits of recursion in simplifying code and solving naturally recursive problems.

Uploaded by

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

Unit – 4 : Recursion

Introduction:
Recursion is defined as defining anything in terms of itself. Recursion is used to solve the problem involving
iteration (multiple expectations) in reserve order loop structure helps to carry out certain tasks a number of times
fill the given condition is satisfied. But how to make a complete function execution repeatedly in terms of itself.
Recursion is an alternative to iteration the technique is useful both for definition of mathematical function and
data structure for example: factorial of number, fibbonices number, Tower of Hanoi, cheese etc.

Need of Recursion
Recursion is a technique with the help of which we can reduce the length of our code and make it easier to read
and write. It has certain advantages over the iteration technique. A task that can be defined with its similar subtask,
recursion is one of the best solutions for it. For example; The Factorial of a number.

[Data Structure and Algorithm ©Raj Kumar Shrestha] Page 1


Types of Recursion:
1) Direct Recursion
When a function calls itself within the same function repeatedly, it is called the direct recursion.

Structure of the direct recursion


directFun()
{
// write some code
directFun();
// some code
}

2) Indirect Recursion
When a function is mutually called by another function in a circular manner, the function is called
an indirect recursion function.
Structure of the indirect recursion

void indirectRecFun1()
{
// Some code...
indirectRecFun2();
// Some code...
}
void indirectRecFun2()
{
// Some code...
indirectRecFun1();
// Some code...
}

Basic requirement of recursion:-


✓ Base case:- which the solution can be stated non recursively
o The statement that solve the problem in base case also a termination a condition of a problem.
o Values of the input variables for which we perform no recursive calls are called base cases (there
should be at least one base case)
✓ General case:- The case for which the solution is expressed in terms of smaller version of itself
o the rest of the condition is known as general case condition the logic needed to reduce the size of
the problem.
o make a recursive call, with some parameter or other measure that decreases or moves towards the
base case
o ensure that sequence of calls eventually reaches the base case

[Data Structure and Algorithm ©Raj Kumar Shrestha] Page 2


//Factorial of Given Number
//Using Recursive Function
#include<stdio.h>
#include<conio.h>

int factorial(int n)
{
if(n==0)
return 1;
else
return n*factorial(n-1);
}
void main()
{
int num;
clrscr();
printf("Enter the number to be insert: ");
scanf("%d",&num);
printf("\n %d",factorial(num));
getch();
}

Fibonacci series using recursion:

//Fibonacci Series
//Using Recursive Function
#include<stdio.h>
#include<conio.h>
int fibo(int n)
{
if (n==1||n==2)
return 1;
else
return (fibo(n-1)+fibo(n-2));
}

[Data Structure and Algorithm ©Raj Kumar Shrestha] Page 3


void main()
{
int num,i;
clrscr();
printf("Enter the term: ");
scanf("%d",&num);

for(i=0;i<num;i++)
{
printf("\n %d",fibo(num));
}
getch();
}

The Recursion Principle

The basic principle of recursion:


1. Must have a base case.
2. Each function call will have a return. When the program flow to a level or execution at the end of recursion,
it will shift to the previous level of recursion to continue.
3. Recursive function, in statements before the recursive call and the called function at all levels have the same
order.
4. Function calls at each level has its own local variables
5. Recursive function, recursive call statement in the statement after the execution of the order and each called
function in reverse order.
6. Although each level of recursion has its own variables, but the function code and will not be copied.
7. Recursive function must contain a statement to terminate the recursive calls.

Example: Fibonacci is a typical recursive case:


Fib(0)=0[Basic] Fib(1)=1 [basic information]
For all n>1 integer: Fib(n)=(Fib(n-1)+Fib(n-2)) [recursive definition]

Iteration vs. Recursion:


[Data Structure and Algorithm ©Raj Kumar Shrestha] Page 4
On the basis Recursion Iteration
of

Basic Recursion is the process of calling a In iteration, there is a repeated execution of the
function itself within its own code. set of instructions. In Iteration, loops are used
to execute the set of instructions repetitively
until the condition is false.

Syntax There is a termination condition is The format of iteration includes initialization,


specified. condition, and increment/decrement of a
variable.

Termination The termination condition is defined Here, the termination condition is defined in
within the recursive function. the definition of the loop.

Code size The code size in recursion is smaller The code size in iteration is larger than the
than the code size in iteration. code size in recursion.

Infinite If the recursive function does not meet Iteration will be infinite, if the control condition
to a termination condition, it leads to of the iteration statement never becomes false.
an infinite recursion. There is a chance On infinite loop, it repeatedly used CPU cycles.
of system crash in infinite recursion.

Applied It is always applied to functions. It is applied to loops.

Speed It is slower than iteration. It is faster than recursion.

Usage Recursion is generally used where It is used when we have to balance the time
there is no issue of time complexity, complexity against a large code size.
and code size requires being small.

Time It has high time complexity. The time complexity in iteration is relatively
complexity lower. We can calculate its time complexity by
finding the no. of cycles being repeated in a
loop.

Stack It has to update and maintain the stack. There is no utilization of stack.

Memory It uses more memory as compared to It uses less memory as compared to recursion.
iteration.

Overhead There is an extensive overhead due to There is no overhead in iteration.


updating and maintaining the stack.

Disadvantages of recursion
1. Not all problems have recursion solution.
2. Recursion problems are not efficient for memory utilization and execution speed of problems.

[Data Structure and Algorithm ©Raj Kumar Shrestha] Page 5


Tower of HANOI (TOH):-

In data structure like linked list, stacks, trees, quicksort, recursion is more handly. In certain problems like
Tower of Hanoi, recursion may be the only solution.

It is a game problem. There will be three different sized disks. Each disk has a hole in the center. So that it can
be stacked on any of the towers. Call three towers as x,y and z. At the beginning of the games, the disks are
stacked on the x towers, that is the largest sized disk on the bottom and the smallest sized disk on top. For n=3
disks.

Rules of the games


i) Transferring the disks from the source tower to the destination tower such that at any point of
transformation no larger size disk is placed on the smaller one.
ii) Only one disk may be moved at a time.

Recursive Definition
It is clear that the movement of disk is from x tower to the y tower. And the z tower is used for intermediate
assuming there is only one disk its movement is straightforward that is:
➢ Move the disk from x tower to y tower. Now consider n = 2 disks. The transferring of these two disks to
the y tower is done as follows.
➢ Move the first disk from the x tower to the z tower. Next, move the disk stacked on the z tower to the y
tower. Since it holds true for the number of disks, n = 1 and n = 2 therefore we can generalized this and
prove that it holds for all disks.
Assuming that initially all disk are stored on the x tower and transferring all these to the y tower can be
recursive defined as follows:
i) Move the top (n-1) disk from the x tower to the z tower.
ii) Move the nth disk to z tower.
iii) Move the (n-1) disk stacked on the z tower to the y tower.

Algorithm for TOH problem:


Let’s consider move ‘n’ disks from source peg (A) to destination peg (C), using intermediate peg (B) as
auxiliary.
1. Assign three pegs A, B & C

[Data Structure and Algorithm ©Raj Kumar Shrestha] Page 6


2. If n==1
Move the single disk from A to C and stop.
3. If n>1
a) Move the top (n-1) disks from A to B.
b) Move the remaining disks from A to C
c) Move the (n-1) disks from B to C
4. Terminate

Implementation of TOH using C:


#include<stdio.h>
#include<conio.h>

void hanoi(int, char, char, char);


int main()
{
clrscr();
hanoi(3,'A','B','C');
getch();
return 0;
}
void hanoi(int n, char rodFrom, char rodMiddle, char rodTo)
{
if(n>=1)
{
hanoi(n-1, rodFrom, rodTo, rodMiddle);
printf("Disk %d moved from %c to %c \n",n,rodFrom,rodTo);
hanoi(n-1,rodMiddle,rodFrom,rodTo);
}
}

For more details about TOH:


https://www.youtube.com/watch?v=VSa5t_LK8pc&t=459s

Greatest common devisor (GCD) using recursion:

The solution to find the greatest common divisor (GCD) for the given two numbers by using the recursive
function is as follows −

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.
[Data Structure and Algorithm ©Raj Kumar Shrestha] Page 7
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.
//program to implement gcd using recursion using c.
#include <stdio.h>
#include<conio.h>
int gcd(int n1, int n2);
int main() {
int n1, n2, div;
printf("Enter two positive integers: ");
scanf("%d %d", &n1, &n2);
div=gcd(n1,n2);
printf("G.C.D of %d and %d is %d.", n1, n2, div);
getch();
return 0;
}

int gcd(int n1, int n2) {


if (n2 != 0)
return gcd(n2, n1 % n2);
else
return n1;
}

Search Tree:
In computer science, a search tree is data structure in whose nodes data values can be stored from some ordered
set, which is such that in an in-order traversal of the tree the nodes are visited in ascending order of the stored
values. Each sub-tree of a search tree is by itself again a search tree.

A search tree is a data structure used in computer programming to contain and organizes a list of data. Each
search tree is comprised of an ordered set of nodes. These nodes can be connected to zero or more other nodes.
The individual nodes contain some data as well as links to any other nodes. The data that is contained in the
nodes of the tree is very often ordered in some way to allow efficient algorithms to search for, insert and
remove nodes with ease.

The nodes of a search tree are described with following terms. The top of tree, where the first node is located, is
called the root. If a node contains links to sub-nodes, that node is known as a parent. Nodes that are beneath the
parent are called children, and any node that has no child nodes is called a leaf. So, a root node is identified
because it does not have a parent, and leaf nodes will have no children.

A program is able to move through a tree searching for data by starting at a particular node, performing a
conditional check and then moving to the next logical node if the required data is not present. Depending on the
data structure used, this search can take a variable amount of time. If the search tree is organized during the
process of adding and removing nodes, the search can be very fast. When a tree is assembled randomly, is
unsorted or allows multiple parents, the search trees can take a very long time.
[Data Structure and Algorithm ©Raj Kumar Shrestha] Page 8
Advantages of recursion
• The code may be easier to write.
• To solve such problems which are naturally recursive such as tower of Hanoi.
• Reduce unnecessary calling of function.
• Extremely useful when applying the same solution.
• Recursion reduce the length of code.
• It is very useful in solving the data structure problem.
• Stacks evolutions and infix, prefix, postfix evaluations etc.

Disadvantages of recursion
• Recursive functions are generally slower than non-recursive function.
• It may require a lot of memory space to hold intermediate results on the system stacks.
• Hard to analyze or understand the code.
• It is not more efficient in terms of space and time complexity.
• The computer may run out of memory if the recursive calls are not properly checked.

[Data Structure and Algorithm ©Raj Kumar Shrestha] Page 9

You might also like