In this tutorial, you will learn to queue program in c which can help to understand insert and delete an element in the queue. Queue stored in memory with use array in c programming.
In case of deletion of elements, take place with the front you only increase your front with "front=front+1" but if front and rear both are at the same place then a front and rear both shifted to "front=-1" and "rear=-1".
Insertion and deletion in queue in data structure algorithm
In case of insertion of elements, the first element in the queue takes place in the queue then your front and rear at "front=-1" and "rear=-1" then you have to shift both with an increment of +1 and your front and rear at "front=0" and "rear=0" then you insert your first element otherwise your "front=0" is fixed and increment your "rear=rear+1" to insert more.In case of deletion of elements, take place with the front you only increase your front with "front=front+1" but if front and rear both are at the same place then a front and rear both shifted to "front=-1" and "rear=-1".
Algorithm: Insertion in Queue-Array
- Start
- If (rear = = size-1)
- printf("Queue is Overflow");
- Else
- If (front == -1)
- front=0;
- rear=rear+1;
- Q[rear]=item;
- Else
- rear=rear+1;
- Q[rear]=item;
- End
Algorithm: Deletion in Queue-Array
- Start
- If (front == -1 && rear == -1)
- printf("Queue is Underflow");
- Else
- If (front > rear)
- front = -1;
- rear = -1;
- Else
- item=Q[rear];
- printf("%d",item);
- front=front+1;
- End
Queue program in c data structure
#include<stdio.h>#define size 50 void insert(); void delete(); void display(); int queue[size]; int rear = - 1; int front = - 1; main() { int choice; while (1) { printf("1.Insert element to QUEUE \n"); printf("2.Delete element from QUEUE \n"); printf("3.Display all elements of QUEUE \n"); printf("4.Quit \n"); printf("Enter your choice : "); scanf("%d", &choice); switch (choice) { case 1:insert(); break; case 2:delete(); break; case 3:display(); break; case 4:exit(1); default:printf("Wrong choice \n"); } } } void insert() { int item; if (rear == size - 1) printf("Queue Overflow \n"); else { if (front == - 1) front = 0; printf("Inset the element in queue : "); scanf("%d", &item); rear = rear + 1; queue[rear] = item; } } void delete() { if (front == - 1 || front > rear) { printf("Queue Underflow \n"); } else { printf("Element deleted from queue is : %d\n", queue[front]); front = front + 1; } } void display() { int i; if (front == - 1) printf("Queue is empty \n"); else { printf("Queue is : \n"); for (i = front; i <= rear; i++) printf("%d ", queue[i]); printf("\n"); } }
OUTPUT
Above we provided information on queue program in c. If you have any problem please comment below.