Write a program in C for Queue using array implementation.

Algorithm :
Step1: Define a array which stores queue elements.

Step 2: The operations on the queue are
a) INSERT data into the queue
b) DELETE data out of queue

Step 3: INSERT DATA INTO queue.
3a. Enter the data to be inserted into queue.
3b. If TOP is NULL.
The input data is the first node in queue.
TOP points to that node.
3c. If TOP is NOT NULL.
The link of TOP points to the new node.
TOP points to that node.

Step 4: DELETE DATA FROM queue.
4a. If TOP is NULL.
The queue is empty.
4b.If TOP is NOT NULL.
The link of TOP is the current TOP.
The pervious TOP is popped from queue.

Step 5. The queue represented by linked list is traversed to display its content.


 Implementation of above program:
# include<stdio.h>
# define MAX 5
int queue_arr[MAX];
int rear = -1;
int front = -1;
main()
{
int choice;
while(1)
{
printf("1.Insert\n");
printf("2.Delete\n");
printf("3.Display\n");
printf("4.Quit\n");
printf("Enter your choice : ");
scanf("%d",&choice);
switch(choice)
{
case 1 : insert(); break;
case 2 : del(); break;
case 3: display(); break;
case 4: exit(1);
default:
printf("Wrong choice\n");
}/*End of switch*/
}/*End of while*/
}/*End of main()*/

insert()
{
int added_item;
if (rear==MAX-1)
printf("Queue Overflow\n");
else
{
if (front==-1) /*If queue is initially empty */
front=0;
printf("Input the element for adding in queue : ");
scanf("%d", &added_item);
rear=rear+1;
queue_arr[rear] = added_item ;
}
}/*End of insert()*/

del()
{
if (front == -1 || front > rear)
{
printf("Queue Underflow\n");
return ;
}
else
{
printf("Element deleted from queue is : %d\n", queue_arr[front]);
front=front+1;
}
}/*End of del() */

display()
{
int i;
if (front == -1)
printf("Queue is empty\n");
else
{
printf("Queue is :\n");
for(i=front;i<= rear;i++)
printf("%d ",queue_arr[i]);
printf("\n");
}
}/*End of display() */

Output of the above program:

1.Insert
2.Delete
3.Display
4.Quit
Enter your choice:1

Input the element for adding in queue :10

1.Insert
2.Delete
3.Display
4.Quit
Enter your choice:1

Input the element for adding in queue :20

1.Insert
2.Delete
3.Display
4.Quit
Enter your choice:1

Input the element for adding in queue :30

1.Insert
2.Delete
3.Display
4.Quit
Enter your choice:1

Input the element for adding in queue :40

1.Insert
2.Delete
3.Display
4.Quit
Enter your choice:3

Queue is :
40
30
20
10

1.Insert
2.Delete
3.Display
4.Quit
Enter your choice:2


Element deleted from queue is :10

1.Insert
2.Delete
3.Display
4.Quit
Enter your choice:3

Queue is :
40
30
20

1.Insert
2.Delete
3.Display
4.Quit
Enter your choice:4


Thanks
Mukesh Rajput
Mukesh Rajput

Mukesh Rajput

I am a Computer Engineer, a small amount of the programming tips as it’s my hobby, I love to travel and meet people so little about travel, a fashion lover and love to eat food, I am investing a good time to keep the body fit so little about fitness also..

Post A Comment:

0 comments: