Wednesday, 8 February 2017

Implementation of Queue Operations in C program

Queue is an abstract data structure, somewhat similar to Stacks. Unlike stacks, a queue is open at both its ends. One end is always used to insert data (enqueue) and the other is used to remove data (dequeue). Queue follows First-In-First-Out methodology, i.e., the data item stored first will be accessed first.

#include <stdio.h>
#define MAX 100
int que[MAX];
int size=-1,popped_item;
void insert(int item);
int delete();
void traverse();
int main()
{
       int ch,choice,item;
       do
       {
             printf("\n--Main Menu--");
             printf("\n1. Insert an element");
             printf("\n2. Delete an element");
             printf("\n3. Traverse the queue");
             printf("\nEnter your choice: ");
             scanf("%d",&choice);
             switch(choice)
             {
                  case 1: printf("\nEnter the element you want to insert: ");
                          scanf("%d",&item);
                          insert(item);
                          break;
                  case 2: popped_item=delete();
                          printf("\n\nThe deleted element is: %d",popped_item);
                          traverse();
                          break;
                  case 3: traverse();
                           break;
                  default: printf("\nYou have entered the wrong choice, wanna try again ??");

             }
             printf("\nDo you want to continue[1/0] ??? ");
             scanf("%d",&ch);
       }while(ch==1);
       return 0;
}
void insert(int item)
{
       if(size==MAX-1)
       {
            printf("\nQueue is in overflow condition, Insertion is not possible !");
       }
       else
       {
            size=size+1;
            que[size]=item;
       }
}
int delete()
{
       int i;
       if(size==-1)
       {
            printf("\nQueue is in underflow condition, Deletion is not possible !");
       }
       else
       {
            popped_item=que[0];
            for(i=0;i<=size-1;i++)
            {
                 que[i]=que[i+1];
            }
            size=size-1;
            return popped_item;
       }
}
void traverse()
{
       int i;
       printf("\nThe Modified Queue is: \n\n");
       for(i=0;i<=size;i++)
       {
             printf("%d  ",que[i]);
       }
}

Output:

 


EmoticonEmoticon