Past exam question: 2065 Shrawan (Regular / Back), Q1(b)
Open in the Padhaiko appQuestion
Write an algorithm for enque and dequeue operations in a queue.
Solution
Array-Based Queue Algorithms (Q[0..MAX-1], initially front = 0, rear = -1):
Algorithm ENQUEUE(Q, val):
1. If rear == MAX - 1:
Print "Queue Overflow"
Return
2. rear = rear + 1
3. Q[rear] = val
4. Return
Algorithm DEQUEUE(Q):
1. If front > rear: // or rear == -1 when empty
Print "Queue Underflow"
Return -1
2. val = Q[front]
3. front = front + 1
4. If front > rear: // queue just became empty: reset pointers
front = 0; rear = -1
5. Return val
(In a circular queue, wrap indices using (index + 1) % MAX with front == -1 for empty and (rear + 1) % MAX == front for full.)
Answer:
ENQUEUE checks overflow, advances rear, and stores Q[rear] = val; DEQUEUE checks underflow, reads Q[front], advances front (resetting when empty), and returns the item—both in time.