Exp 4 - Dsa Lab File

You might also like

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 18

EXPERIMENT NO-4: QUEUE

BASIC IMPLEMENTATION OF LINEAR QUEUE IN C PROGRAMMING


Linear queue also known as a simple queue is the most basic version of a queue. Here,
insertion of an element i.e., the Enqueue operation takes place at the rear end and removal of
an element i.e., the Dequeue operation takes place at the front end. Here, problem is that if we
pop some item from front and then rear reach to the capacity of the queue and although there
are empty spaces before front means the queue is not full but as per conditions in is Full ()
function, it will show that the queue is full then.

ALGORITHM: -
FIFO Principle of Queue:

 A Queue is like a line waiting to purchase tickets, where the first person in line
is the first person served. (i.e., First come first serve).
 Position of the entry in a queue ready to be served, that is, the first entry that
will be removed from the queue, is called the front of the queue
(sometimes, head of the queue), similarly, the position of the last entry in the
queue, that is, the one most recently added, is called the rear (or the tail) of the
queue.

Basic Operations
Queue operations also include initialization of a queue, usage and permanently deleting the
data from the memory.

The most fundamental operations in the queue ADT include: enqueue(), dequeue(), Full(),
Empty(). These are all built-in operations to carry out data manipulation and to check the
status of the queue.
Queue uses two pointers − front and rear. The front pointer accesses the data from the front
end (helping in enqueueing) while the rear pointer accesses data from the rear end (helping in
dequeuing).
Insertion operation: enqueue()
The enqueue() is a data manipulation operation that is used to insert elements into the stack.
The following algorithm describes the enqueue() operation in a simpler way.
Algorithm
1 − START
2 – Check if the queue is full.
3 − If the queue is full, produce overflow error and exit.
4 − If the queue is not full, increment rear pointer to point the next empty space.
5 − Add data element to the queue location, where the rear is pointing.
6 − return success.
7 – END

Deletion Operation: dequeue()


The dequeue() is a data manipulation operation that is used to remove elements from the
stack. The following algorithm describes the dequeue() operation in a simpler way.
Algorithm
1 – START
2 − Check if the queue is empty.
3 − If the queue is empty, produce underflow error and exit.
4 − If the queue is not empty, access the data where front is pointing.
5 − Increment front pointer to point to the next available data element.
6 − Return success.
7 – END

The Full() Operation


The Full() operation verifies whether the stack is full.

Algorithm
1 – START
2 – If the count of queue elements equals the queue size, return true
3 – Otherwise, return false
4 – END
The Empty() operation

The Empty() operation verifies whether the stack is empty. This operation is used to check
the status of the stack with the help of top pointer.

Algorithm
1 – START
2 – If the count of queue elements equals zero, return true
3 – Otherwise, return false
4 – END

IMPLEMENTATION:-

#include<stdio.h>
#include<stdlib.h>
#define maxsize 5
int enqueue();
void dequeue();
void display();
int front = -1, rear = -1;
int queue[maxsize];
int main ()
{
int choice;
while(choice != -1)
{ printf("\n1.Insert an element\n2.Delete an element\n3.Display the queue\n4.Exit\n");
printf("\nEnter your choice:");
scanf("%d",&choice);
switch(choice)
{
case 1:
enqueue();
break;
case 2:
dequeue();
break;
case 3:
display();
break;
case 4:
exit(0);
break;
default:
printf("\nEnter valid choice!\n");
}
}
return 0;
}
int enqueue()
{
int item;
printf("\nEnter the element:\n");
scanf("\n%d",&item);
if(rear == maxsize-1)
{
printf("\nOVERFLOW\n");
return 0;
}
if(front == -1 && rear == -1)
{
front = 0;
rear = 0;
}
else
{
rear = rear+1;
}
queue[rear] = item;
printf("\nValue inserted:%d",queue[rear]);

}
void dequeue()
{
int item;
if (front == -1 || front > rear)
{
printf("\nUNDERFLOW\n");
return;
}
else
{
item = queue[front];
if(front == rear)
{
front = -1;
rear = -1 ;
}
else
{
front = front + 1;
}
printf("\nValue deleted.");
}

void display()
{
int i;
if(rear == -1)
{
printf("\nEmpty queue!\n");
}
else
{ printf("\nThe elements in the queue are:\n");
for(i=front;i<=rear;i++)
{
printf("%d\n",queue[i]);
}
}
}

OUTPUT: -
APPLICATIONS OF LINEAR QUEUE: -
1. Print Queue: In operating systems, a print queue manages print jobs from multiple users.
Jobs are placed in the queue and printed in the order they were submitted.

2. Task Scheduling: Linear queues are used in task scheduling algorithms, ensuring that
tasks are executed in the order they are received or according to their priority.

3. Breadth-First Search (BFS): BFS, a graph traversal algorithm, uses a queue to explore
nodes level by level in a graph. It is commonly used in graph-related problems like finding
the shortest path in an unweighted graph.

4. Resource Sharing: Queues are used to manage access to shared resources, such as a CPU
in a multi-tasking operating system or network bandwidth.

5. Order Processing: E-commerce websites and retail stores often use queues to manage the
order processing system. Orders are processed in the order they are received.

6. Customer Service: In call centres and customer service applications, customer queries and
support requests are often placed in a queue to be handled by the next available
representative.

7. Data Buffering: Queues are used in data buffering to store and process incoming data
streams, ensuring that data is processed at a controlled rate.

8. Simulations: Queues are commonly used in computer simulations to model various real-
world scenarios, such as traffic flow, waiting lines in supermarkets, or customer service
centres.

9.Web Servers: Web servers use queues to manage incoming HTTP requests, ensuring that
they are processed in an orderly manner.

10. Messaging Systems: Messaging systems, like message queues, use linear queues to order
and manage messages sent between applications or services.

11. Inventory Management: In inventory and stock management systems, linear queues can
be used to track and manage orders for restocking products.
12. Background Job Processing: Linear queues are employed to manage background jobs in
applications. For example, sending emails in a batch process, generating reports, or
performing data synchronization tasks.

13. Traffic Management: Linear queues can be used in traffic signal control systems to
manage the order of vehicles at intersections, toll booths, or border crossings.

14. IoT (Internet of Things): In IoT applications, queues can be used to manage and process
sensor data or device commands in a structured and orderly manner.

CONCLUSION: -
Linear queues provide a simple and efficient way to manage and manipulate data in a
sequential manner. They are relatively easy to implement and understand, making them a
valuable tool in various computing applications. However, it's essential to consider their
limitations, such as fixed size and the potential for overflow or underflow, when using them
in practical scenarios. In situations where a dynamic size and more complex operations are
required, other data structures like linked lists or circular queues may be more suitable.

BASIC IMPLEMENTATION OF CIRCULAR QUEUE IN C PROGRAMMING


In a circular queue, the element of the queue act as a circular ring.
The working of a circular queue is similar to the linear queue except for the fact that the last
element is connected to the last element. Its advantages are that the memory is utilised in a
better way. This is because if there is an empty space i.e.,
If no element is present at a certain position in the queue, then an element can be easily added
at that position using module capacity(%n).

ALGORITHM: -

Circular Queue Operations

The circular queue work as follows:

 two pointers FRONT and REAR


 FRONT track the first element of the queue
 REAR track the last elements of the queue
 initially, set value of FRONT and REAR to -1

1. Enqueue Operation

 check if the queue is full


 for the first element, set value of FRONT to 0
 circularly increase the REAR index by 1 (i.e. if the rear reaches the end, next it would
be at the start of the queue)
 add the new element in the position pointed to by REAR
2. Dequeue Operation

 check if the queue is empty

 return the value pointed by FRONT


 circularly increase the FRONT index by 1
 for the last element, reset the values of FRONT and REAR to -1

However, the check for full queue has a new additional case:

 Case 1: FRONT = 0 && REAR == SIZE - 1


 Case 2: FRONT = REAR + 1
The second case happens when REAR starts from 0 due to circular increment and when its
value is just 1 less than FRONT, the queue is full.

IMPLEMENTATION: -

#include <stdio.h>
#include<stdlib.h>
# define max 6
int queue[max];
int front=-1;
int rear=-1;
void enqueue(int element)
{
if(front==-1 && rear==-1)
{
front=0;
rear=0;
queue[rear]=element;
}
else if((rear+1)%max==front)
{
printf("Queue is overflow.");
}
else
{
rear=(rear+1)%max;
queue[rear]=element;
}
}

int dequeue()
{
if((front==-1) && (rear==-1))
{
printf("\nQueue is underflow.");
}
else if(front==rear)
{
printf("\nThe dequeued element is %d", queue[front]);
front=-1;
rear=-1;
}
else
{
printf("\nThe dequeued element is %d", queue[front]);
front=(front+1)%max;
}
}
void display()
{
int i=front;
if(front==-1 && rear==-1)
{
printf("\n Queue is empty..");
}
else
{
printf("\nElements in a Queue are:\n");
while(i<=rear)
{
printf("%d\n", queue[i]);
i=(i+1)%max;
}
}
}
int main()
{
int choice,data;

while(choice!=-1)
{
printf("\n1.Insert an element");
printf("\n2.Delete an element");
printf("\n3.Display the element");
printf("\n4.Exit");
printf("\nEnter your choice:");
scanf("%d", &choice);
switch(choice)
{

case 1:
printf("Enter the element which is to be inserted:");
scanf("%d", &data);
enqueue(data);
break;
case 2:
dequeue();
break;
case 3:
display();
break;
case 4:
exit(0);
break;

}
}
return 0;
}

OUTPUT:-
APPLICATIONS OF CIRCULAR QUEUE: -
1. Data Buffering: Circular queues are often used in buffering data streams. For example, in
multimedia applications, audio and video data can be buffered in a circular queue to ensure a
smooth playback, as the oldest data is overwritten when the buffer is full.

2. Task Scheduling: In operating systems, circular queues are used for task scheduling.
Processes waiting to be executed are placed in a circular queue, and the scheduler cycles
through them, giving each process a time slice.

3. Print Spooling: Circular queues can be used in print spoolers to manage print jobs. When
multiple print jobs are submitted, they can be placed in a circular queue to ensure that each
job gets its turn to be printed.

4. Simulation of Processes: Circular queues are used in simulations where entities (e.g.,
customers in a queue, cars in a traffic simulation) are processed in a cyclic manner,
mimicking real-world scenarios.

5. Keyboard Input Buff: In systems that require keyboard input (e.g., computer keyboards),
circular queues can be used to store keystrokes. This allows the system to handle keypresses
in the order they were received.

6. Memory Management: Operating systems may use circular queues to manage memory
allocation. When memory is allocated and freed, the available memory blocks can be
organized in a circular queue to efficiently manage memory allocation.

7. Communication Systems: Circular queues are used in communication systems for data
transmission and reception. Data packets or messages can be stored in a circular queue,
ensuring that incoming and outgoing data is processed sequentially.

8. Caching: In computer systems, circular queues can be employed to implement cache


eviction policies. The least recently used (LRU) items can be maintained in a circular queue,
and when the cache is full, the LRU item is replaced.

9. Resource Management: Circular queues can be used to manage resources in various


scenarios, such as managing connections in a network or allocating resources in a multi-user
environment.
10. Traffic Management: In network and traffic management systems, circular queues can
be used to schedule and control the flow of data packets or vehicles through a network or
intersection.

CONCLUSION: -
A circular queue is a versatile and efficient data structure that offers several advantages in
various applications. It overcomes the limitations of a traditional linear queue by reusing the
space in a circular fashion, thereby reducing memory wastage. Circular queues are
particularly useful in scenarios that requires efficient, fixed-size data storage and retrieval.
Their advantages in memory utilization and constant-time operations make them a valuable
addition to the programmer's toolkit.

You might also like