Your implementation may not be the most efficient way of using an array to implement a queue, but given that you've decided to implement it.
- Related Questions & Answers
- Selected Reading
A queue is an abstract data structure that contains a collection of elements. Queue implementsthe FIFO mechanism i.e. the element that is inserted first is also deleted first. In other words, theleast recently added element is removed first in a queue.
A program that implements the queue using an array is given as follows −
Example
The output of the above program is as follows
In the above program, the function Insert() inserts an element into the queue. If the rear is equalto n-1, then the queue is full and overflow is displayed. If front is -1, it is incremented by 1. Thenrear is incremented by 1 and the element is inserted in index of rear. This is shown below −
In the function Delete(), if there are no elements in the queue then it is underflow condition.Otherwise the element at front is displayed and front is incremented by one. This is shownbelow −
In the function display(), if front is -1 then queue is empty. Otherwise all the queue elements aredisplayed using a for loop. This is shown below −
The function main() provides a choice to the user if they want to insert, delete or display the queue. According to the user response, the appropriate function is called using switch. If theuser enters an invalid response, then that is printed. The code snippet for this is given below −