Wednesday 5 March 2014

Queue Implementation using arrays

#include<stdio.h>
#include<stdlib.h>
#define MAX 4 //you can increase or decrease the
//queue size by modifying MAX value

void Enqueue(int Q[], int item);
void Dequeue(int Q[]);
void display_Q(int Q[]);

int Front=-1,Rear=-1;


int main(void)
{
int item,choice;
int Q[MAX];

while(1)
{
printf("\n1.Insert an item into Q\n2.Delete an item from Q"
"\n3.Display Queue\n4.Exit\n\nEnter the choice as given : ");
scanf("%d",&choice);

switch(choice)
{
case 1:printf("\nEnter the element : ");
scanf("%d",&item);
Enqueue(Q,item);
break;
case 2:Dequeue(Q);
break;
case 3:display_Q(Q);
break;
case 4:exit(0);
break;
default: printf("\n\nYou have entered wrong choice !\n\n");
}
}
return 0;
}

void Enqueue(int Q[], int item)
{

if(Rear == MAX-1)
{
if(Front == 0)
printf("\nQueue is full, you can't enter any more elemetns !\n\n");
else
printf("\nYou can't insert untill queue will not be empty !\n");
}
else
{
Rear++;
Q[Rear]= item;
if(Front==-1)
Front = 0;
}
}

void Dequeue(int Q[])
{
int x;
if(Front == -1)
printf("\nQueue is Empty, you can't delete any more element !\n\n");
else
{
x = Q[Front];
Front++;
if(Front == Rear+1)
{
Front = -1;
Rear = -1;
}
printf("\n%d is deleted form Queue !\n",x);
}
}

void display_Q(int Q[])
{
int i;
if(Front == -1)
printf("\nQueue is Empty !\n\n");
else
for(i=Front; i<=Rear; i++)
printf(" %d",Q[i]);
}

//Note => once you started deletion You can't insert another
//element in queue untill the queue is empty.
//cause it is array implementation and it is also not a circular queue


Output:


Queue_array

No comments:

Post a Comment