# Circular Queue Data Structure

## Circular Queue

Circular queue is a modified form of queue in which the front and rear pointers move circularly.
Instead of starting from -1, now front and rear start from 0.

Representation of circular queue: ``````class Queue{
int arr
int front, rear;
int size;
};

Queue(int n)
{
front = 0;
rear  = 0;
size =n;
}
``````

## Operations

To make front and rear move circularly, after rear reaches (size-1 ) position, it must be reset to 0.
To do this, '%' is used.
Working of mod operator can be seen:
Let size = 5.
| Rear = | (Rear+1)%size |
|:–:|:–:|
| 0 | (0+1)%7 = 1 |
| 1 | (1+1)%7 =2|
| 2 | (2+1)%7 =3|
| : | : |
| 4 | (4+1)%5 =0 |

Hence when rear points to (size-1), it gets reset to 0.

## Working of circular queue : ### Enqueue

• Elements are inserted from the rear end as usual.
• If rear reaches (size-1), it is reset to zero
• Insertion can't be done at the index where front is pointing

Only (size-1) spaces can be utilized in Circular queue.

``````void enqueue(int x)
{
if((rear+1)%size == front)
print("Queue is Full");
else
{
rear=(rear+1)%size;
arr[rear]=x;
}
}
``````

### Dequeue

``````int dequeue()
{
int x=-1;
if(front==rear)
print("Queue is Empty")
else
{
front=(front+1)%size;
x=arr[front];
}
return x;
}
``````

### Display

``````void Display()
{    int i= front+1;
do
{
print(arr[i]);
i=(i+1)%size;
}while(i!=(rear+1)%size);
}
``````

Complexity for all operations on circular queue is O(1).

Scroll to Top

### Full Stack Integrated Bootcamp Free Trial

• Please enter a number from 7000000000 to 9999999999.
{"ft_lang_label":"__label__en","ft_lang_prob":0.7264488,"math_prob":0.97909373,"size":1339,"snap":"2021-21-2021-25","text_gpt3_token_len":428,"char_repetition_ratio":0.13782771,"word_repetition_ratio":0.0,"special_character_ratio":0.36071694,"punctuation_ratio":0.14878893,"nsfw_num_words":0,"has_unicode_error":false,"math_prob_llama3":0.9857413,"pos_list":[0,1,2,3,4,5,6],"im_url_duplicate_count":[null,null,null,3,null,3,null],"WARC_HEADER":"{\"WARC-Type\":\"response\",\"WARC-Date\":\"2021-06-14T15:02:21Z\",\"WARC-Record-ID\":\"<urn:uuid:8e7367fa-7a24-4d95-8829-fb5f017e6453>\",\"Content-Length\":\"129286\",\"Content-Type\":\"application/http; msgtype=response\",\"WARC-Warcinfo-ID\":\"<urn:uuid:37d79f83-cdf5-45ff-86d4-6737675a8a0a>\",\"WARC-Concurrent-To\":\"<urn:uuid:a15f53c0-81dd-418c-97d7-cd6b6fe0c0e5>\",\"WARC-IP-Address\":\"45.79.125.9\",\"WARC-Target-URI\":\"https://prepfortech.in/interview-topics/queue/circular-queue-data-structure\",\"WARC-Payload-Digest\":\"sha1:S2WCFJROU355ICH6QTBJ7KX3UOZO4H2S\",\"WARC-Block-Digest\":\"sha1:VD64TUPBGIUCR3FE7BY6KEGCEW22ERJY\",\"WARC-Identified-Payload-Type\":\"text/html\",\"warc_filename\":\"/cc_download/warc_2021/CC-MAIN-2021-25/CC-MAIN-2021-25_segments_1623487612537.23_warc_CC-MAIN-20210614135913-20210614165913-00539.warc.gz\"}"}