C Programming language

adplus-dvertising
C - Queue Static implementation
Previous Home Next

Static Implementation of queue is generally done by using arrays. So we must be sure about the exact number of the elements we want to store in the queue, as it is static implementation is done through arrays, so memory is to be allocated as static and we cannot change the capacity of the queue dynamically. In this implementation the beginning of the queue will become Front and the last element will be Rear.

So we can say by seeing the following relation between the front and rear the total no. of elements that are contained in a queue can be calculated as:

(Rear-Front) + 1;// and if rear, it means the queue will always be empty.

As we know that the static implementation of the queue is done by using Array Data structure. So a code snippet shows how we can delete and add an element in a queue using array data structure.

#include <stdio.h>
#include<conio.h>
#define<stdlib.h>
#define MAXSIZE 17
void enqueue();
void dequeue();
void display();
int queue[MAXSIZE];
int front=-1;
int rear=-1;
void main()
{
int choice;
char ch;
clrscr();
printf("Program for various operations on Queue using arrays");
do
{
 printf("\n1. Enqueue");
 printf("\n2. Dequeue");
 printf("\n3. Display");
 printf("Enter your choice :");
 scanf("%d",&choice);
 switch(choice)
{
     case 1: enqueue();
         break;
     case 2: dequeue();
         break;
     case 3: display();
         break;
 default : printf("\nwrong choice made");
    }
printf("\ndo you want to continue y/n");
fflush(stdin);
scanf("%c",&ch);
}
while ((char=='y')||(char=='Y'));
getch();
}
void enqueue()
{
int info;
if(rear>=MAXSIZE)
{
    printf("\nQueue Overflow");
break;
}
else
{
     printf("\nEnter the element you want to insert to queue");
 scanf("\n%d", &info);
 rear=rear+1;                     /* increasing rear to accommodate new element*/
 queue[rear]=info;                  /* placing the new element to the rear */
    }
}
void dequeue()
{
int info;
if(front==-1)                                        /*checking the underflow condition */
{
     printf("\n the queue is empty");
 break;
}
else
{
     info=queue[front];                               /*placing front element to info */
 front=front+1;                               /*incrementing the front value */
 printf("\n the deleted item is %d", info);   /*returning the deleted value*/
    }
}
void display()
{
 int i;
 if(rear==-1)                                        /*checking the underflow condition */
 printf("\n queue is empty");
 else
{
     printf("\nthe queue is diplayed as :")
 for(i=front;i<=rear;i++)                    /*traversing the queue */
{
     printf("%d",queue[i]);
}
    }
}
Previous Home Next