# Thread: Questions regarding circular queues

1. ## Questions regarding circular queues

I've given a code example that I've written that will create and fill a queue. That part is in the bottom most code section works ok. It's here for completeness.
I've some questions regarding circular queues for which I am having a difficult time wrapping my little mind around.

1) I need to create a function that clears the queue. So I wrote a function that does exactly what CreateQueue does. My question regarding this is wouldn't setting q->count to 0 do the same thing and is that really the more appropriate thing to do?
Code:
```void ClearQueue(Queue *q){
q->count=0;
q->front=0;
q->rear=-1;
}```
2) if I wanted to get to the front of the Queue, I guess I could just traverse backwards and decrement q->count until it reaches 0. Is that the correct approach?

3) Lastly, if you were asked to traverse the queue (God only knows why) but would you first make a copy of q->count, then reset to 0 and move through the queue incrementally till q->count = copy?

Code:
```Given the definitions:
#define MAXQUEUE 3
typedef char QueueEntry;

typedef struct queue{
int count;
int front;
int rear;
QueueEntry entry[MAXQUEUE];
} Queue;

// create the queue
void CreateQueue(Queue *q){
q->count=0;
q->front=0;
q->rear=-1;
}
//append items to the queue
void Append(QueueEntry x, Queue *q){
if(QueueFull(q))
Error("Cannot append an entry to a full queue");
else{
q->count++;
q->rear=(q->rear + 1) % MAXQUEUE;
q->entry[q->rear]=x;
}
}

//creates and fills the queue
int main(){
Queue q;
QueueEntry item;

CreateQueue(&q);

item='A';
Append(item, &q);
item='B';
Append(item,&q);
item='C';
Append(item,&q);

return 1;
}```

2. Adding an element to a queue is called 'enqueue' and removing an element is called 'dequeue'.

1) Yes. That's the best way of doing it. If you wanted to zero out the whole thing you could use the memset function and set everything to 0 then set rear to -1. Otherwise, simply set count, front to 0 and rear to -1.

2) If you wanted to get to the front of the q, just use the front variable you defined to get there. No need to decrement count. If you were to dequeue then simply increment front and decrease count. Just make sure you handle the boundary conditions appropriately.

3) Do not reset count to 0. Simply start with a local index and increment until it equals count.

Popular pages Recent additions