Circular queue code output

Code

#include<stdio.h>

#define SIZE 5

typedef struct
{
    int front,rear,arr[SIZE];
}queue;

queue q;

void init()
{
    q.front=q.rear=-1;
}

int isEmpty()
{
    if(q.front==-1)
        return 1;
    return 0;
}

int isFull()
{   
    if(q.front == (q.rear+1)%SIZE)
        return 1;
    return 0;
}

void enqueue()
{
    int element;

    do
    {
        if(isFull())
        {
            printf("\nCircular queue overflow");
            break;
        }

        printf("\nEnter element to be enqueued ");
        scanf("%d",&element);

        if(isEmpty())
            q.front++;

        q.rear = (q.rear+1) % SIZE;
        q.arr[q.rear] = element;

        printf("\nEnqueue more elements ? ");

        fflush(stdin);

    }while(getchar()=='y');
}

int dequeue()
{
    int element = q.arr[q.front];

    if(isEmpty())
    {
        printf("\nQueue underflow.");
        return -1;
    }
    else 
    {
        if(q.front == q.rear)
            init();
        else
            q.front = (q.front+1) % SIZE;
        return element;
    }
}

void display()
{
    int i;

    if(isEmpty())
    {
        printf("\nQueue is Empty");
        return;
    }

    printf("\n");

    for(i=q.front;i!=q.rear;i=(i+1)%SIZE)
        printf("%d ",q.arr[i]);

    printf("%d",q.arr[i]);              //print rear element
}

int main()
{
    int ch,element;

    init();

    do
    {
        printf("\n1.Enqueue\n2.Dequeue\n3.Display\n\nEnter choice ");
        scanf("%d",&ch);

        switch(ch)
        {
            case 1:
                   enqueue();
                   break;

            case 2:
                   element = dequeue();
                   if(element!=-1)printf("\nElement dequeued = %d",element);
                   break;

            case 3:
                  display();
                  break;
         }   

         printf("\nContinue ? ");
         fflush(stdin);

     }while(getchar()=='y');

    return 0;
}


O/P

Circular-queue-output



No comments:

Post a Comment