DS Module 2
DS Module 2
• Recursion:
- Factorial
- GCD
- Fibonacci Sequence
- Tower of Hanoi
• Queue:
- Definition
- Representation
- Operations
- Queue Variants:
o Circular Queue.
o Priority Queue,
- Applications of Queues.
- Programming Examples.
1
Data Structures with Algorithms 22MCA13
Module -2: Recursion and Queue
1. Recursion
I
• Definition
Recursion is a process of solving a problem by reducing the given problem into smaller
version of the same problem.
or
Recursion is a technique that solves a problem by dividing a problem into smaller
problem of the same type.
Recursive function:
Function which calls or invokes itself again and again until certain condition is reached
is called as a recursive function.
• Advantages
1. Recursive solutions are shorter and simpler.
2. Code is easier to use.
3. Follows divide and conquer to solve problems.
• Disadvantages:
4. Recursion is difficult concept to some programmers.
5. Recursion uses system stack. If the system stack is limited, it is difficult to
implement recursion.
6. Uses more memory and time to execute.
7. It is difficult to find errors.
In general,
A procedure or function that is run over and over for a definite number of times is recursion.
Many problems - Factorial, GCD, Fibonacci, Tower of Hanoi, etc. - use recursive technique
to solve. This approach is useful for both the definition of mathematical functions
(recurrence relation) and for the definition of data structure.
2
Data Structures with Algorithms 22MCA13
Module -2: Recursion and Queue
- Factorial
- GCD
- Fibonacci Sequence
- Tower of Hanoi
3
Data Structures with Algorithms 22MCA13
Module -2: Recursion and Queue
Factorial of a Number
In Mathematics, factorial is an important function, which is used to find how many ways things
can be arranged or the ordered set of numbers. The well-known interpolating function of the
factorial function was discovered by Daniel Bernoulli. In short, a factorial is a function, that
multiplies a number by every number below it.
What is Factorial?
In Mathematics, Factorials are just products. An exclamation (!) mark indicates the factorial.
Factorial is a multiplication operation of natural numbers with all the natural numbers that are
less than it.
Factorial Notation
The multiplication of all positive integers says "n", that will be smaller than or equivalent to n is
known as the factorial. The factorial of a positive integer is represented by the symbol "n!".
Factorial Formula
The formula to find the factorial of a number is: n! = n * (n-1) * (n-2) * (n-3) *……* 3 * 2 * 1
It may seem funny that multiplying no numbers together results in 1, but let's follow the pattern
backwards from, say, 4! like this:
41 = 24
31 = 6
2! = 2
1! = 1
0! = 1
And in many equations using O! = 1 just makes sense.
• Factorial of a Number
Recursive definition:
- factorial (n) = 1 if n=O or n =1
- factorial (n) = n * factorial (n-1) if n>l
4
Data Structures with Algorithms 22MCA13
Module -2: Recursion and Queue
Where is Factorial
Used? Example:1
Example: how many ways can we arrange letters (without repeating)?
For 1 letter "a" here is only 1 way: a
For 2 letters "ab" there are 1X2=2 ways: ab, ba
For 3 letters "abc" there are 1X2X3=6 ways: abc acb cab bac bca cba
For 4 letters "abed" there are 1x2x3x4=24 ways: (try it yourself!)
etc
Now ... how many ways can we arrange no letters? Just one way, an empty space: So O! =1
5
Data Structures with Algorithms 22MCA13
Module -2: Recursion and Queue
#include<stdio.h>
#include<conio.h>
void main()
{
int n;
long int result;
//clrscr();
result= fact(n );
//getch();
}
Output:
6
Data Structures with Algorithms 22MCA13
Module -2: Recursion and Queue
The Greatest Common Divisor of two integers a and b, not both zero, is the largest of the
common divisors of a and b. It is denoted as gcd (a, b).
7
Data Structures with Algorithms 22MCA13
Module -2: Recursion and Queue
Q2. Write C program to find GCD of two numbers using Euclidean method and recursion
#include<stdio.h>
if (y == 0)
{
return x;
}
else
{
return gcd_algorithm(y, (x % y));
}
}
int main()
{
int num1, num2, gcd;
printf("\nEnter two numbers to find gcd using Euclidean algorithm:
");
scanf("%d%d", &num1, &num2);
gcd = gcd_algorithm(num1, num2);
8
Data Structures with Algorithms 22MCA13
Module -2: Recursion and Queue
9
Data Structures with Algorithms 22MCA13
Module -2: Recursion and Queue
1
0
Data Structures with Algorithms 22MCA13
Module -2: Recursion and Queue
• Fibonacci Series
Recursive definition:
- fib(n) = n if n=O or n
- fib(n) = fib(n-2)+fib(n-1) =1 if n>=2
Q4. Write C program to print Fibonacci series for n terms using recursion
#include <stdio.h>
#include <conio.h>
getch();
}
Output:
1
1
Data Structures with Algorithms 22MCA13
Module -2: Recursion and Queue
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:
2. 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.
1
2
Data Structures with Algorithms 20MCA11
Module -2: Recursion and Queue
void main()
{
int n; II Number of
disks
Output:
13
Data Structures with 22MCA13
Module -2: Recursion andAlgorithms
Queue
[Link]
Queue:
Definition
Representation
Operations
Queue Variants:
Circular Queue,
Priority Queue,
Double Ended Queue
Applications of Queues.
Programming Examples.
14
Data Structures with 22MCA13
Module -2: Recursion andAlgorithms
Queue
• Definition
"A Queue is a Linear collection of list in which insertion and deletions takes place at
different ends. The end at which insertion takes place is called the rear end and at end at
which deletions takes place is called the front end".
• Properties of Queue:
15
Data Structures with Algorithms 22MCA13
Module -2: Recursion and Queue
1. Linear Queue
2. Circular Queue
3. Priority Queue
16
Data Structures with Algorithms 22MCA13
Module -2: Recursion and Queue
void insert_rearQ()
{
if (rear == SIZE-1)
{
printf( "\n ** Queue is Overflow** \n");
}
else
{
if (front==-1)
{
front=0;
}
printf("Enter the element to be inserted into queue:");
scanf("%d", &ele);
rear++;
Q[rear]=ele;
printf("\n Inserted -> %d", ele);
}
}
17
Data Structures with Algorithms 22MCA13
Module -2: Recursion and Queue
void delete_frontQ()
{
if (front==-1)
{
printf ("**Queue is Underflow **\n");
}
else
{
printf("\n Deleted item is: %d \n", Q[front]);
front++;
if(front>=rear){
front=rear=-1;
}
}
}
void display( )
{
int i;
if(rear==-1)
{
printf("\n ** Queue is Empty...\n");
}
printf(" Queue elements are:\n");
for(i=front; i<= rear; i++)
printf("\n%d ", Q[i]);
}
18
Data Structures with Algorithms 22MCA13
Module -2: Recursion and Queue
Q7. Write a C program to demonstrate the Queue operations. Display appropriate messages
as Queue Overflow and Queue Underflow. enqueue(), dequeue(), display()
/* Queue Implementation */
#include<stdio.h>
#include<stdlib.h>
# define SIZE 3
int Q[SIZE], choice, ele;
int front=-1;
int rear=-1;
int main(){
while(1)
{
printf("\nEnter your choice:\n ");
scanf("%d", &choice);
switch(choice)
{
case 1:
/* Insert an item/element in queue */
insert_rearQ();
break;
case 2:
{
/* Remove an item from queue */
delete_frontQ;
break;
}
case 3:
{
display();
break;
}
case 4:
exit(0);
19
Data Structures with Algorithms 22MCA13
Module -2: Recursion and Queue
default:{
printf("\n Please Enter a Valid Choice ( 1/2/3/4)");
}
}
}
}
void insert_rearQ()
{
if (rear == SIZE-1)
{
printf( "\n ** Queue is Overflow** \n");
return;
}
else
{
if (front==-1)
{
front=0;
}
printf("Enter the element to be inserted into queue:");
scanf("%d", &ele);
rear++;
Q[rear]=ele;
printf("\n Inserted -> %d", ele);
}
}
//dequeue -> function for deleting element
void delete_frontQ()
{
if (front==-1)
{
printf ("**Queue is Underflow **\n");
}
else
{
printf("\n Deleted item is: %d \n",Q[front]);
front++;
if(front>=rear){
front=rear=-1;
}
}}
void display( )
{
20
Data Structures with Algorithms 22MCA13
Module -2: Recursion and Queue
int i;
if(rear==-1)
{
printf("\n ** Queue is Empty...\n");
}
printf(" Queue elements are:\n");
for(i=front; i<= rear; i++)
printf("\n%d ", Q[i]);
}
Output:
21
Data Structures with Algorithms 22MCA13
Module -2: Recursion and Queue
inserted when all the elements are deleted from the queue.
Now, if the first three members are de-queued (deleted/removed) from the front
Where the queue remains full, but we cannot insert a new element because the
back of the queue (right hand side) remains as it was before. This is the major
limitation of a classical queue, i.e., even if there is space available at the front of the
22
Data Structures with Algorithms 22MCA13
Module -2: Recursion and Queue
Circular Queue
• Definition
"Circular queue is a linear data structure where the last node is connected back to the first
node to make a circle. Elements are added at the rear end and the elements are deleted at
front end of the queue".
- In circular queue the last node is connected back to the first node to make a circle.
- Circular linked list fallows the First In First Out principle.
- Elements are added at the rear end and the elements are deleted at front end of
the queue.
- Both the front and the rear pointers points to the beginning of the array.
- It is also caIled as "Ring buffer".
23
Data Structures with Algorithms 22MCA13
Module -2: Recursion and Queue
int CQ[max];
int front=0, rear=-1, count=0;
void del()
{
int item;
if(count == 0)
{
printf("\nCQ is underflow!!!\n");
return;
}
count--;
item= CQ[front];
front= (front+1) % max;
24
Data Structures with Algorithms 22MCA13
Module -2: Recursion and Queue
void display()
{
int i,f;
if(count == 0)
{
printf("\nCQ is Empty!!!\n");
return;
}
f = front;
printf("\nCQ elements are:");
for(i=1; i<=count; i++)
{
printf("\n%d",CQ[f]);
f = (f + 1) % max;
}
printf("\n");
}
void main()
{
int ch, item;
//clrscr();
while(1)
{
printf("\n 1:Insert Rear\n 2:Delete Front\n 3:Display\n 4:Exit\n");
switch(ch)
25
Data Structures with Algorithms 22MCA13
Module -2: Recursion and Queue
{
case 1:
printf("\nEnter an item to insert:");
scanf("%d",&item);
insert(item);
break;
case 2:
del();
break;
case 3: display();
break;
case 4: exit(0);
break;
default:
printf("Invalid choice!!!");
break;
}
//getch();
}
}
Output:
26
Data Structures with Algorithms 22MCA13
Module -2: Recursion and Queue
Priority Queue
• Definition
#define MAX 3
#define n 3
typedef struct
{
int items[MAX];
int front;
int rear;
}QUEUE;
q[p].rear++;
q[p].items[q[p].rear] = elem;
if(q[p].front == -1)
q[p].front=0;
27
Data Structures with Algorithms 22MCA13
Module -2: Recursion and Queue
for(p=0;p<n;p++)
{
if(q[p].front != -1)
{
temp=q[p].items[q[p].front];
if(q[p].front==q[p].rear)
q[p].front=q[p].rear=-1;
else
q[p].front++;
break;
}
}
return temp;
}
void main()
{
QUEUE q[n];
int i,elem,ch,pri;
int item;
//clrscr();
for(i=0;i<n;i++)
q[i].front = q[i].rear = -1;
while(1)
{
printf("------------------- ");
printf("\n\[Link]\n\t2 Display\n\t3 Delete\n\t4 Exit\n");
printf("------------------- ");
28
Data Structures with Algorithms 22MCA13
Module -2: Recursion and Queue
scanf("%d",&elem);
qinsert(q,pri-1,elem);
break;
case 2:
for(pri=0;pri<n;pri++)
{
printf("\n Priority :%d\n",pri+1);
for(i=q[pri].front;(i<=q[pri].rear)&&(i>=0);i++)
printf(" %d",q[pri].items[i]);
printf("\n");
}
break;
case 3 :
item= qdelete(q);
if(item==-1)
printf("\n Queue is empty and Q is UNDERFLOW\n");
else
printf("\n Deleted element %d\n",item);
break;
default :
printf("\n Invalid option\n");
exit(0);
break;
}
}
}
29
Data Structures with Algorithms 22MCA13
Module -2: Recursion and Queue
• Definition
"Double-ended queue is an abstract data type for which elements can be added to or
removed from either the front or rear end".
- New items can be added at either the front or the rear and existing items can be
removed from either the front or the rear end.
- It is also often called as a deque or head-tail linked list.
• Memory representation
REAR/FRONT FRONT/REAR
Figure: Double Ended Queue representation and operations
• Properties
30
Data Structures with Algorithms 22MCA13
Module -2: Recursion and Queue
• Basic Double Ended Queue operations
• Types of deque
1. Input-restricted deque:
Where deletion can be made from both ends, but insertion can be made at only one end.
2. Output-restricted deque:
Where insertion can be made at both ends, but deletion can be made from only one end.
void main()
{
int i,x,op,n;
dequeue q;
initialize(&q);
do
{
printf("\[Link]\[Link](rear)\[Link](front)\[Link](rear)
\[Link](front)"); printf("\[Link]\
[Link]\n\nEnter your choice:"); scanf("%d",&op);
switch(op)
{
case 1: printf("\nEnter number of elements:");
scanf("%d",&n);
initialize(&q); printf("\
nEnter the data:");
for( i=0;i<n;i++)
{
scanf("%d",&x);
if(full(&q))
{
printf( "\nQueue is full!!");
exit(0);
}
enqueueR(&q,x);
}
break;
if(full(&q))
{
printf("\nQueue is full!!");
exit(0);
}
enqueueR(&q,x);
break;
32
Data Structures with Algorithms 22MCA13
Module -2: Recursion and Queue
case 3: printf("\nEnter the element to be inserted:");
scanf("%d",&x);
if(full(&q))
{
printf( "\nQueue is full!!");
exit(0);
}
enqueueF(&q,x);
break;
case 4: if(empty(&q))
{
printf("\nQueue is empty!!");
exit(0);
}
x=dequeueR(&q);
printf("\nElement deleted is %d\n",x);
break;
case 5: if(empty(&q))
printf("\nQueue is empty!!");
exit(0);
}
x=dequeueF(&q);
printf("\nElement deleted is %d\n",x);
break;
case 6: print(&q);
break;
default: break;
}
}while(op!=7);
}
33
Data Structures with Algorithms 22MCA13
Module -2: Recursion and Queue
return(0);
}
return(0);
}
34
Data Structures with Algorithms 22MCA13
Module -2: Recursion and Queue
x=P->data[P->front];
return(x);
}
x=P->data[P->rear];
if(P->rear==P->front)
initialize(P);
else
P->rear=(P->rear-l+MAX)%MAX;
return(x);
}
i=P->front;
while(i!=P->rear)
{
printf("\n%d",P->data[i]);
i=(i+1)%MAX;
}
printf("\n%d\n",P->data[P->rear]);
}
35
Data Structures with Algorithms 22MCA13
Module -2: Recursion and Queue
Recursion
3 Write a recursive Program to Find the greatest common deviser of two integers. 6
Queue
1 Write a function in C to simulate the working of linear queue for the following 8
operations.
i) insert ii) delete iii) display.
2 What is the need for using circular array to implement queues? 4
3 List the applications of liner queue. Implement insert and delete operations. 8
4 What is circular queue 8
Write C function to implement circular queue
a) insert front b) remove front c) display list
5 Write algorithms to insert into and delete elements from a doubly ended queue 8
6 List the applications of Stack and Queue. 4
7 What is Deque? 4
8 What is priority queue? Explain about different types of priority queue. 5
36