Linear Queue using an Array
#include<stdio.h>
#include<stdlib.h>
#define
MAX 5
int
front = -1;
int
rear = -1;
int
q[MAX];
void
insert();
void
delete();
void
display();
void
main()
{
int ch;
while(1)
{
printf("\n\nMenu\n1.Insert\n2.Delete\n3.Display\n4.exit");
printf("\nEnter
your choice:\t");
scanf("%d",&ch);
switch(ch)
{
case 1: insert();
display();
` break;
case
2: delete();
display();
break;
case
3: display();
break;
case
4: exit(0);
default: printf("\nInvalid
Choice\n");
}
}
}
void
insert()
{
int item;
if(rear
== MAX-1)
{
printf("\n~~~Queue
Overflow~~~");
return;
}
printf("\nEnter the item to to
be inserted:");
scanf("%d", &item);
rear = rear+1;
q[rear] = item;
}
void
delete()
{
int item;
if(front == rear)
{
printf("\n~~~Queue
Underflow~~~");
return;
}
front
= front+1;
item = q[front];
printf("\nThe item that got
deleted is: %d", item);
}
void
display()
{
int i;
printf("\nfront = %d, rear =
%d",front, rear);
if(front == rear)
{
printf("\nQueue is
empty\n");
return;
}
else
{
printf("\nElements
of the queue are: ");
for(i=front+1;
i<=rear;i++)
printf("%d\t",q[i]);
}
}
Output:
Menu
1.Insert
2.Delete
3.Display
4.exit
Enter
your choice: 1
Enter the item to to be inserted: 11
front = -1, rear = 0
Elements of the queue are: 11
Menu
1.Insert
2.Delete
3.Display
4.exit
Enter
your choice: 1
Enter the item to to be inserted: 22
front = -1, rear = 1
Elements of the queue are: 11 22
Menu
1.Insert
2.Delete
3.Display
4.exit
Enter
your choice: 1
Enter
the item to to be inserted: 33
front = -1, rear = 2
Elements of the queue are: 11 22 33
Menu
1.Insert
2.Delete
3.Display
4.exit
Enter
your choice: 1
Enter the item to to be inserted: 44
front = -1, rear = 3
Elements of the queue are: 11 22 33 44
Menu
1.Insert
2.Delete
3.Display
4.exit
Enter
your choice: 1
Enter the item to to be inserted: 55
front = -1, rear = 4
Elements of the queue are: 11 22 33
44
55
Menu
1.Insert
2.Delete
3.Display
4.exit
Enter
your choice: 1
~~~Queue Overflow~~~
front = -1, rear = 4
Elements of the queue are: 11 22 33 44 55
Menu
1.Insert
2.Delete
3.Display
4.exit
Enter
your choice: 2
The item that got deleted is: 11
front = 0, rear = 4
Elements of the queue are: 22 33
44 55
Menu
1.Insert
2.Delete
3.Display
4.exit
Enter
your choice: 2
The item that got deleted is: 22
front = 1, rear = 4
Elements of the queue are: 33 44 55
Menu
1.Insert
2.Delete
3.Display
4.exit
Enter
your choice: 2
The item that got deleted is: 33
front = 2, rear = 4
Elements of the queue are: 44 55
Menu
1.Insert
2.Delete
3.Display
4.exit
Enter your choice: 2
The item that got deleted is: 44
front = 3, rear = 4
Elements of the queue are: 55
Menu
1.Insert
2.Delete
3.Display
4.exit
Enter
your choice: 2
The item that got deleted is: 55
front = 4, rear = 4
Queue is empty
Menu
1.Insert
2.Delete
3.Display
4.exit
Enter
your choice: 2
~~~Queue Underflow~~~
front = 4, rear = 4
Queue is empty
Menu
1.Insert
2.Delete
3.Display
4.exit
Enter
your choice: 4