# Size of Circular Queue [closed]

I am Implementing a Queue using circular arrays in C language .The Implementation uses one empty position to indicate that the queue is full.That is if the rear is two position behind front. The condition is we cant use a variable to count the entries in the queue as we insert or delete . I have created this function to find the size of queue with Time Complexity Big-Oh(n) because it starts with front and goes upto rear in a loop .

int QueueSize(Queue *q)
{
if(QueueEmpty(q))
{
return 0;
}
else{
int count=0;
for(int i=q->front;;i=(i+1)%MAXQUEUE)
{
count++;
if(i==q->rear) break;
}
return count;
}
}


Is there a way to find the size of queue in constant time ? Elements are inserted from rear and deleted from front ! My Queue starts from 0 and assume maximum queue size is 6 in below example

10 Appended at position 0
20 Appended at position 1
30 Appended at position 2
40 Appended at position 3
50 Appended at position 4
10 Removed from position 0
20 Removed from position 1
60 Appended at position 5
70 Appended at position 0
30 Removed from position 2
40 Removed from position 3
80 Appended at position 1
90 Appended at position 2
Queue Size:5
Position:4  Element:50 (front)
Position:5  Element:60
Position:0  Element:70
Position:1  Element:80
Position:2  Element:90 (rear)


## closed as off-topic by Yuval Filmus, David Richerby, Evil, fade2black, Rick DeckerAug 24 '17 at 13:33

This question appears to be off-topic. The users who voted to close gave this specific reason:

• "Questions about software development or programming tools are off-topic here, but can be asked on Stack Overflow." – Yuval Filmus, David Richerby, Evil, fade2black, Rick Decker
If this question can be reworded to fit the rules in the help center, please edit the question.

• This seems to be very implementation-dependent, and so more of a programming question. Try computing q->rear - q->front. – Yuval Filmus Aug 22 '17 at 15:40
• Should I post the whole code ? Or ask It at stack overflow ? – Pradeep Kumar Aug 22 '17 at 15:45
• If your question involves code then it belongs on stackoverflow. – Yuval Filmus Aug 22 '17 at 15:45
• No you just need to know the implementation details . – Pradeep Kumar Aug 22 '17 at 15:49
• I don't understand the question. In a circular buffer, the number of elements in it can be computed in constant time. (It's basically the distance between the pointers, wrapping around and $\pm 1$.) (And that much doesn't seem to language dependent, @YuvalFilmus?) – Raphael Aug 22 '17 at 16:36

Suppose that the queue consists of elements $Q[a],\ldots,Q[b]$, where $Q = Q,\ldots,Q[n]$ is an array of length $n$. If $a \leq b$ then the queue contains $b-a+1$ elements, and if $a > b$ then the queue contains $b-a+1+n$ elements.
• It doesn't contain more than $n$ elements. I encourage you to try some example such as $a=n$ and $b=1$. The queue in this case contains $b-a+1+n = 2$ elements, $Q[n]$ and $Q$. – Yuval Filmus Aug 22 '17 at 17:29