I designed a circular queue program which provides queue management system. Everything works fine, except that in some cases, I can't print the queue.
My code:
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#define CAPACITY 5
#define MAX_STRING_SIZE 40
#define TRUE 1
#define FALSE 0
struct queue
{
char items[CAPACITY][MAX_STRING_SIZE];
int front,rear ;
};
void cqinsert(struct queue * , char name[]);
void cqdelete(struct queue *);
int empty(struct queue *);
int main(void)
{
int order;
char name[MAX_STRING_SIZE];
int menu;
char operation;
int x;
struct queue q;
q.front = q.rear = CAPACITY - 1;
do{
printf(">>Please enter an operation number from the given list:\n");
printf("[1]-Customer Entry\n[2]-Customer Exit\n[3]-Waiting Customers List\n[4]-Exit\n");
scanf("%d",&menu);
switch(menu) {
case 1: printf("Enter customer name: ");
scanf("%s",&name);
cqinsert(&q,name);
break;
case 2: cqdelete(&q);
break;
case 3: if(q.front==CAPACITY-1) {
order = 1;
for(int i=0;i<=q.rear;i++) {
printf("[%d]-%s\n",order,q.items[i]);
order++;
}
break;
}
else {
order=1;
for(int i=q.front+1;i<=q.rear;i++) {
printf("[%d]-%s\n",order,q.items[i]);
order++;
}
break;
}
}
}while(menu!=4);
system("pause");
return 0;
}
int empty(struct queue *pq)
{
return((pq->front == pq->rear) ? TRUE : FALSE);
}
void cqdelete(struct queue *pq)
{
if (empty(pq)) {
printf("Queue is empty !");
exit(1);
}
if (pq->front == CAPACITY - 1)
pq->front = 0;
else
(pq->front)++;
printf("\n -----> %s is deleted from the queue. \n\n",pq->items[pq->front]);
}
void cqinsert(struct queue *pq , char name[])
{
printf("\n -----> %s is inserted to queue. \n\n",name);
if (pq->rear == CAPACITY - 1)
pq->rear = 0;
else
(pq->rear)++;
if (pq->rear == pq->front) {
printf("Queue is full !");
exit(1);
}
strcpy(pq->items[pq->rear],name);
}
When q.front is greater than q.rear, case 3 (the printing) doesn't print anything.
For example after the inputs below I can't display queue elements:
- 4 times CUSTOMER ENTRY(insert)
- 2 times CUSTOMER EXIT(delete)
- 2 times CUSTOMER ENTRY(insert)
- and select Waiting Customers List ---> here is the problem: it doesn't display elements in the queue.
You can use the following inputs to apply those steps:
1
c1
1
c2
1
c3
1
c4
2
2
1
c5
1
c6
3
4
How can I display the queue, even when q.front is greater than q.rear?