How to implement Queue and realize various operations to be performed on it.

avatar
(Edited)

f653b2fa-6790-4d95-b5cf-1eafcce38bda_Data_Queue.png

In last post i talked about Stack so in this post i will talk about queue.

AIM:To Implement Queue and realize various operations to be performedon

Algorithm:

• Start
• Include all header files that are used in the program.
• Declaring all user-defined functions that are used to implement queues.
• Creating a one-dimensional array
• Defining two integer variables 'front' and 'rear'
• deciding for the operations to be executed using a case statement.
• defining all of the functions that will be used to carry out the operations

Enqueue :

  1. If rear = size (A) – 1
  2. Return Queue is full
  3. Else if Is Empty ()
  4. {
  5. front = rear =0
  6. A [rear] = x
  7. }
  8. Else
  9. {
  10. rear = rear +1
  11. A [rear] = x
  12. }

Dequeue :

  1. {
  2. if Is Empty()
  3. return
  4. else if front = rear
  5. front = rear = -1
  6. else
  7. front = front + 1
  8. }

Display:

  1. Define n
  2. If Front = -1 and Rear = -1
  3. print "Queue is Empty"
  4. Else
  5. for i = Front to Rear
  6. print queue[i]
  7. End for

Code:

#include <stdio.h>
#include <stdlib.h>
int size = 5;
int queue[5];
int front = -1, Rear = -1;
void isEmpty();
void Front();
void enqueue();
void dequeue();
void show();

void isEmpty() {
if(front == -1 && Rear == -1){
printf("\nEmpty Queue\n");
}
else{
printf("\nNot Empty\n");
}
}

void Front(){
printf("Element in Front is : %d\n",queue[0]);
}

void enqueue(){
int n;
if(Rear == size - 1 ){
printf("\nQueue overflow\n");
}
else{
if(front == -1 && Rear == -1){
printf("\nElement to be inserted in the Queue: ");
scanf("%d", &n);
front = front + 1;
Rear = Rear + 1;
queue[Rear] = n;
}
else{
printf("\nElement to be inserted in the Queue: ");
scanf("%d", &n);
Rear = Rear + 1;
queue[Rear] = n;
}
}
}

void dequeue(){
if(front == -1 && Rear == -1){
printf("\nQueue is Empty\n");
}
else{
printf("\nElement deleted from the queue : %d\n", queue[front]);
front = front + 1;
}
}

void display(){
if (front == - 1 && Rear == -1){
printf("\nEmpty Queue \n");
}
else
{
printf("\nElement in Queue : \n");
for (int i = front; i <= Rear; i++)
printf(" %d ", queue[i]);
}
printf("\n");
}

void main(){
int num;
printf("\n---20BCE2929---");
while(1) {
printf("\n1.isEmpty\n2.Front\n3.enqueue\n4.dequeue\n5.Display\n6.Exit");
printf("\nEnter your choice : ");
scanf("%d",&num);
if(num == 1){
isEmpty();
}
else if(num == 2){
Front();
}
else if(num == 3){
enqueue();
}
else if(num == 4){
dequeue();
}
else if(num == 5){
display();
}
else if(num == 6){
exit(0);
}
}
}

Posted with STEMGeeks



0
0
0.000
0 comments