C program to create queue using array.

Posted by Mangesh on April 11, 2018

program in c to implement queue using array.

Description :

Queue is a container that is use to store objects. It use principle of First In First Out. A queue is a data structure where we add elements at the back and remove elements from the front. In that way a queue is like “waiting in line”: the first one to be added to the queue will be the first one to be removed from the queue. This is also called a FIFO (First In First Out) data structure. Queues are common in many applications. Common example are buffers for network communication that temporarily store packets of data arriving on a network port.

Program :

#include<stdio.h>
#include<conio.h>
#define limit 5
int empty(int head,int tail)
{
  if(head == tail)
    return 1;
  return 0;
}
int full(int head,int tail)
{
  if(head == (tail+1)%limit)
    return 1;
  return 0;
}
void enque(int queue[limit],int data, int *tail)
{
  queue[*tail] = data;
  if(*tail == limit-1)
    *tail = 0;
  else
    *tail = *tail+1;
}
void deque(int *head)
{
  if(*head == limit-1)
    *head=0;
  else
    *head = *head+1;
}
void printarray(int start,int end,int arr[5])
{
  int i;
  printf("Elements in queue are : ");
  if(start<end)
  {
    for(i=start;i<end;i++)
      printf("%d ",arr[i]);
  }
  else
  {
    for(i=start;i<=limit-1;i++)
      printf("%d ",arr[i]);
    for(i=0;i<end;i++)
      printf("%d ",arr[i]);
  }
}

void main()
{
  int queue[limit];
  int front=0,rear=0,data,choice=0;

  do{
  printf("\n\nPress 1 for inerting in queue.");
  printf("\nPress 2 for deleting from queue.");
  printf("\nPress 3 to get value of front and rear of queue.");
  printf("\nEnter your choice : ");
  scanf("%d",&choice);

  switch(choice)
  {
  case 1:
  printf("Enter the data : ");
  scanf("%d",&data);
  if(!full(front,rear))
    enque(queue,data,&rear);
  else
    printf("Queue is already full!!!");
  printarray(front,rear,queue);
  break;
  case 2:
  if(!empty(front,rear))
    deque(&front);
  else
    printf("Queue is already empty!!!");
  printarray(front,rear,queue);
  break;
  case 3:
  printf("Front =  %d, Rear = %d. ",front,rear);
  break;
  case 4 :
  printf("\n Exiting...");
  break;
  default :
  printf("\nInvalid choice...");
  }
}while(choice!=4);
getch();
}

Output :

output for inserting in queue.

c program for Executed and tested in Turbo C 3.2

output for deleting in queue.

c program for Executed and tested in Turbo C 3.2

output to get value of head and tail in queue.

c program for Executed and tested in Turbo C 3.2

Written with from Mangesh.

Related Post
1 C program to create queue using array.
2 C program to implement Queue using linked list.
Latest Post
1 C program to implement Queue using linked list.
2 C program for binary search tree (BST).
3 C program to search an element in linked list.
4 C program for postorder traversal in binary tree.
5 C program for preorder traversal in binary tree.