> For the complete documentation index, see [llms.txt](https://tanias-workspace.gitbook.io/tanias-little-corner/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://tanias-workspace.gitbook.io/tanias-little-corner/problems/implement-queue-using-array.md).

# Implement Queue using array

<figure><img src="/files/hYiPbtq2IPAYIa6pGLzK" alt=""><figcaption></figcaption></figure>

<figure><img src="/files/oK66YEqlhY2n9pOgrgpS" alt=""><figcaption></figcaption></figure>

#### **Key Operations**

* **Enqueue:** Add an element to the rear of the queue.
* **Dequeue:** Remove an element from the front of the queue.
* **Peek/Front:** View the front element without removing it.
* **isEmpty:** Check if the queue is empty.
* **isFull:** Check if the queue is full (important for fixed-size arrays).

#### &#x20;**Implementing the Queue**

&#x20;**Variables**

* **Array `queue[]`:** This array will hold the queue elements.
* **int `front`:** Points to the first element of the queue.
* **int `rear`:** Points to the last element of the queue.
* **int `capacity`:** The maximum size of the queue.
* **int `size`:** Keeps track of the current number of elements in the queue.

<figure><img src="/files/PLjyffuVD0dDAMQn9zCK" alt=""><figcaption></figcaption></figure>

## Full Implementation in C++

```
#include <iostream>
using namespace std;


class Queue { 
private: 
int front, rear, size; 
int capacity; 
int* queue;
public: 
Queue(int cap) { 
capacity = cap; front = size = 0; rear = cap - 1; // Initialize rear to the end 
queue = new int[cap]; }

~Queue() {
    delete[] queue;
}

bool isFull() {
    return (size == capacity);
}

bool isEmpty() {
    return (size == 0);
}

void enqueue(int element) {
    if (isFull()) {
        cout << "Queue is full\n";
        return;
    }
    rear = (rear + 1) % capacity;
    queue[rear] = element;
    size++;
    cout << element << " enqueued to queue\n";
}

int dequeue() {
    if (isEmpty()) {
        cout << "Queue is empty\n";
        return -1;
    }
    int element = queue[front];
    front = (front + 1) % capacity;
    size--;
    return element;
}

int peek() {
    if (isEmpty()) {
        cout << "Queue is empty\n";
        return -1;
    }
    return queue[front];
}
};

int main() { 
Queue q(5);
q.enqueue(10);
q.enqueue(20);
q.enqueue(30);
q.enqueue(40);
q.enqueue(50);

cout << q.dequeue() << " dequeued from queue\n";

cout << "Front item is " << q.peek() << endl;

return 0;
```
