Below is my implementation of a simple queue using arrays.
#include<stdio.h>
#include<stdlib.h>
#define QSIZE 5 //Limit size of queue to just 5 enteries
/*Beginning of prototype for queue functions: Insert, retrieve and display*/
void qdisp(); //Display to queue array contents
void qinsert(); //Insert a element into rear of queue
int qdelete(); //Remove an element from front of queue
/*End of prototyping*/
// Variables
int fe=0,re=0,q[QSIZE],item; //fe(front entry), re(rear entry), q[](queue array), item(element to i/p or delete)
void main()
{
int choice;
while(1)
{
printf("1.Insert element\n2.Remove element\n3.Display element(s)\n4.Exit program\nEnter number for appropriate choice: ");
scanf("%d",&choice);
switch(choice)
{
case 1: printf("Enter value of element: ");
scanf("%d",&item);
qinsert();
break;
case 2: item=qdelete();
printf("Removed \'%d\' from the queue\n",item);
break;
case 3: qdisp();
break;
case 4: exit(0);
/*case default : printf("Wrong choice i/p!");
break;*/
}
}
}
//End of main, beginning for function definitons
void qinsert()
{
if(re==QSIZE-1)
{
printf("Queue Overflow\n");
exit(0);
}
q[re]=item;
re++;
}
int qdelete()
{
if(fe>re)
{
printf("Queue is empty!\n");
exit(0);
}
item=q[fe];
fe++;
return item;
}
void qdisp()
{
int i; //i is loop counter variable
if(fe>re)
{
printf("Queue is empty!\n");
exit(0);
}
printf("Queue items are: \n");
for(i=fe;i<=re;i++)
printf("%d\n",q[i]);
}
I have used initial front and rear entry as 0 since initially in a queue any entry that goes first becomes the last entry as well. However my teacher says I should keep the rear entry as '-1' and while inserting an element into queue, first increment the rear entry index and then add opposing my code of first adding then incrementing. I looked into it and online and till now I don't find how I'm wrong.
Provide me information if I'm wrong or my teacher is?
if(fe>re){ printf("Queue is empty!\n");exit(0);}: but initial satatus is (empty queque, fe = 0, re = 0).