Circular Queue

 

#include <iostream>
#define MAX 5

using namespace std;

class CircularQueue {
private:
    char queue[MAX];
    int front, rear;

public:
    CircularQueue() {
        front = rear = 0;
    }

    // Insert an element into the queue
    void insert(char element) {
        if ((rear+1) % MAX == front) {
            cout << "Queue Overflow! Cannot insert element.\n";
            return;
        }
        queue[rear] = element;
        cout << "Inserted " << element << " into the queue.\n";
        rear = (rear + 1) % MAX;
    }

    // Delete an element from the queue
    void remove() {
        if (front == rear) {
            cout << "Queue Underflow! No elements to remove.\n";
            return;
        }
        cout << "Removed " << queue[front] << " from the queue.\n";
        front = (front + 1) % MAX;
    }

    // Display the status of the queue
    void display() {
        if (front == rear) {
            cout << "Queue is empty.\n";
            return;
        }
        cout << "Queue elements are: ";
        int i = front;
        while (i != rear) {
            cout << queue[i] << " ";
            i = (i + 1) % MAX;
        }
        cout << endl; //"\n"
    }
};

int main() {
    CircularQueue q;
    int choice;
    char element;

    do {
        cout << "\nMenu:\n";
        cout << "1. Insert an element into the queue\n";
        cout << "2. Delete an element from the queue\n";
        cout << "3. Demonstrate overflow situation\n";
        cout << "4. Demonstrate underflow situation\n";
        cout << "5. Display the status of the queue\n";
        cout << "6. Exit\n";
        cout << "Enter your choice: ";
        cin >> choice;

        switch (choice) {
            case 1:
                cout << "Enter the character to insert: ";
                cin >> element;
                q.insert(element);
                break;
            case 2:
                q.remove();
                break;
            case 3:
                cout << "Demonstrating Overflow: Trying to insert more than " << MAX << " elements...\n";
                for (int i = 0; i < MAX + 1; i++) {
                    q.insert('A' + i);
                }
                break;
            case 4:
                cout << "Demonstrating Underflow: Trying to remove from an empty queue...\n";
                q.remove();
                for (int i = 0; i < MAX + 1; i++) {
                    q.remove();
                }
                break;
            case 5:
                q.display();
                break;
            case 6:
                cout << "Exiting...\n";
                break;
            default:
                cout << "Invalid choice. Please enter a number between 1 and 6.\n";
                break;
        }
    } while (choice != 6);

    return 0;
}

Comments