Pages

RevenueHits

Search ~~~~

Tuesday, June 28, 2011

Circular Queue implementation

Circular Queue implementation using C programming.


#include<stdio.h>
int queue[10];
int lowerBound=0;
int upperBound=9;
int front=-1;
int rear=-1;
int size=0;


void addToQueue(int num)                   
{
if(size==(upperBound-lowerBound)+1) return; // queue Full
if(rear<upperBound)
{
rear++;
}
else
{
rear=lowerBound;
}


queue[rear]=num;
size++;
if(front==-1)front=0;
}


int removeFromQueue()
{
int num;
if(size==0)return 0; //queue Empty
num=queue[front];
if(front<upperBound)
{
front++;
}
else
{
front=lowerBound;
}
size--;
return num;


}
int isQueueFull()
{
return size==(upperBound-lowerBound)+1;
}


int isQueueEmpty()
{
return size==0;
}


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;
}
}
}