Circular queue

#include<stdio.h>
#define max 5

int queue[max];
int f=-1,r=-1;

void enqueue(int x)
{
    if((r+1)%max==f)
        printf("Overflow\n");
    else
    {
        if(f==-1&&r==-1)
        {
            f=r=0;
            queue[r]=x;
        }
        else
        {
            r=(r+1)%max;
            queue[r]=x;
        }
    }
}

int dequeue()
{
    int x;
    if(f==-1&&r==-1)
    {
        printf("Underflow\n");
        return -1;
    }
    else
    {
        x=queue[f];
        if(f==r)
        {
            f=r=-1;
            return x;
        }
        else
        {
            f=(f+1)%max;
            return x;
        }
    }
}

void display()
{
    int i;
    for(i=f;i!=r;i=(i+1)%max)
        printf("%d ",queue[i]);
    printf("%d ",queue[r]);
    printf("\n");
}

void main()
{
    int n,a;
    do
    {
        printf("\nEnter\n1.Enqueue\n2.Dequeue\n3.Display\n4.Exit\n");
        scanf("%d",&n);
        switch(n)
        {
            case 1:
                printf("Enter element to insert ");
                scanf("%d",&a);
                enqueue(a);
                break;
            case 2:
                dequeue();
                break;
            case 3:
                display();
                break;
        }
    }while(n!=4);
}

/*Output

Enter
1.Enqueue
2.Dequeue
3.Display
4.Exit
1
Enter element to insert 5

Enter
1.Enqueue
2.Dequeue
3.Display
4.Exit
1
Enter element to insert 6

Enter
1.Enqueue
2.Dequeue
3.Display
4.Exit
3
5 6

Enter
1.Enqueue
2.Dequeue
3.Display
4.Exit
2

Enter
1.Enqueue
2.Dequeue
3.Display
4.Exit
3
6

Enter
1.Enqueue
2.Dequeue
3.Display
4.Exit
4
*/

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s