Coders Packet

C program for implementation of a Queue using an Array

By Srishti Dhaval Patkar

This is a C program which implements the queue operations using an array. The program includes queue operations like Enqueue operation, Dequeue operation, Display and Quit option.

Implementation of a Queue using an Array

This is a C program which implements the queue operations using an array.

The queue operations in the given program are:

1) Enqueue

To insert an element to the queue. In a queue, a new element is always added from the rear of the queue. 

Given below is the function used in the code for enqueue operation. 

First, we take the element to be added to the queue from the user. After that, we check if the queue is full by checking if rear is at the last index of the array. If not, then we add the new element to the index at the rear of the queue and increment the rear by one.

void enqueue()
{
  int new_item;//new element to be enqueued
  if(rear==MAX-1)
  {
    printf("Queue overflow\n");//if queue is already full
  }
  else
  {
    if(front==-1)
    front=0;	
    printf("Enter the number to be entered: ");
    scanf("%d",&new_item);
    rear+=1;//increment rear by 1
    queue[rear]=new_item;//adds new element at the rear
  }	
}

 

2) Dequeue

To delete an element from the queue. In a queue, an element is always deleted from the front of the queue. 

Given below is the function used in the code for dequeue operation. 

First, we check if the queue is empty. If not, then we traverse through the queue using for loop from the index at the front to that at the rear and delete the first element of the queue by shifting all the succeeding elements to the front and decrementing rear by one.

void dequeue()
{
  if(front==-1||front>rear)
    printf("Queue underflow\n");//if queue is empty
  for(int i=front;i<=rear;i++)
  {
    queue[i]=queue[i+1];
  }//removes an element from the front 
  rear-=1;//decrement rear by 1
}

 

3) Display:

To display the elements in the queue.

Given below is the function to display the elements of the queue.

void display()
{
  if(front==-1)
  {
    printf("\nQueue is empty\n");
  }
  else
  {	
    printf("\nThe queue is:\n");
    for (int i=front;i<=rear;i++)
    {
      printf("%d ",queue[i]);//prints the queue elements from front to rear
    }
    printf("\n");
  }
}

 

 

Download Complete Code

Comments

No comments yet