0

C Program to perform different operations on queue.

 

So here we have a program to perform various operations  on Queue elements like 

  • Insert
  • Delete
  • Peek

If you don’t know about queues visit this blog:

https://www.devlopersguide.com/queue-data-structure/

#include<stdio.h> 

#include<conio.h>

#define max 10

int queue[max];

int front=-1,rear=-1;

void insert(void)

{

int num;

printf(“\n enter the no. to be inserted: “);

scanf(“%d”,&num);

if(rear==max-1)

printf(“\n overflow”);

else if(front==-1 && rear==-1)

front=rear=0;

else

rear++;

queue[rear]=num;

}

int delete_element(void)                   // function to delete element

{

int val;

if(front==-1 || front>rear)               // condition to check if Queue is empty

{

printf(“\n underflow”);

return -1;

}

else

{

val=queue[front];

front++;

if(front>rear)

front=rear=-1;

return val;

}

}

int peek(void)                                      // function to peek elements

{

if(front==-1 || front>rear)

{

printf(“\n queue is empty”);

return 1;

}

else

{

return queue[front];

}

}

void display()                                     // function to display elements

{

int i;

printf(“\n”);

if(front==-1 || front>rear)

printf(“\n queue is empty”);

else

{

for(i=front;i<=rear;i++)

printf(“\t %d”,queue[i]);

}

}

int main()

{

int option,val;

clrscr();

printf(“\n ***************************”);

do

{

printf(“\n 1.insert an element”);

printf(“\n 2.delete an element”);

printf(“\n 3.peek”);

printf(“\n 4.display”);

printf(“\n 5.exit”);

printf(“\n enter your option”);

scanf(“%d”, &option);

switch(option)

{

case 1:insert();

break;

case 2:val=delete_element();

if(val!=-1)

printf(“\n the no. deleted is: %d”,val);

break;

case 3:val=peek();

printf(“\n  the first value in queue is: %d”,val);

break;

case 4:display();

break;

}

}while(option!=5);

getch();

return 0;  }

for more programming topics visit:

https://www.devlopersguide.com/category/programming/

ks007

Leave a Reply

Your email address will not be published. Required fields are marked *