Pages

RevenueHits

Search ~~~~

Tuesday, June 28, 2011

Queue using Array


An example of queue using Array

#include<stdio.h>
int queue[10];
int lowerBound=0;
int upperBound=9;
int front=-1;
int rear=-1;
void addToQueue(int num)
{
if(rear==upperBound) return; // queue Full
rear++;
queue[rear]=num;
if(front==-1)front=0;
}
int removeFromQueue()
{
int num,i;
if(rear==-1)return 0; //queue Empty
num=queue[front];
i=0;
while(i<rear)
{
queue[i]=queue[i+1];
i++;
}
rear--;
if(rear==-1)front=-1;
return num;
}

int isQueueFull()
{
return rear==upperBound;
}

int isQueueEmpty()
{
return rear==-1;
}

void main()
{
int ch,num;
while(1)
{
printf("1. Add To Queue\n");
printf("2. Remove From Queue\n");
printf("3. Enter your choice");
scanf("%d",&ch);
if(ch==1)
{
if(isQueueFull())
{
printf("Queue is full\n");
}
else
{
printf("Enter number to add to queue");
scanf("%d",&num);
if(num==0)
{
printf("Cannot add zero to queue\n");
}
else
{
addToQueue(num);
printf("%d added to queue \n",num);
}
}
}
if(ch==2)
{
if(isQueueEmpty())
{
printf("Queue is empty\n");
}
else
{
num=removeFromQueue();
printf("%d removed from queue\n",num);
}
}
if(ch==3)
{
break;
}
}
}

No comments:

Post a Comment