• Source
    1. #include <stdio.h>
    2.  
    3. #define SIZE 5
    4.  
    5. int items[SIZE];
    6. int front = -1, rear =-1;
    7.  
    8. int isFull()
    9. {
    10. if( (front == rear + 1) || (front == 0 && rear == SIZE-1)) return 1;
    11. return 0;
    12. }
    13.  
    14. int isEmpty()
    15. {
    16. if(front == -1) return 1;
    17. return 0;
    18. }
    19.  
    20. void enQueue(int element)
    21. {
    22. if(isFull()) printf("\n Queue is full!! \n");
    23. else
    24. {
    25. if(front == -1) front = 0;
    26. rear = (rear + 1) % SIZE;
    27. items[rear] = element;
    28. printf("\n Inserted -> %d", element);
    29. }
    30. }
    31.  
    32.  
    33. int deQueue()
    34. {
    35. int element;
    36. if(isEmpty()) {
    37. printf("\n Queue is empty !! \n");
    38. return(-1);
    39. } else {
    40. element = items[front];
    41. if (front == rear){
    42. front = -1;
    43. rear = -1;
    44. } /* Q has only one element, so we reset the queue after dequeing it. ? */
    45. else {
    46. front = (front + 1) % SIZE;
    47.  
    48. }
    49. printf("\n Deleted element -> %d \n", element);
    50. return(element);
    51. }
    52. }
    53.  
    54.  
    55.  
    56.  
    57. void display()
    58. {
    59. int i;
    60. if(isEmpty()) printf(" \n Empty Queue\n");
    61. else
    62. {
    63. printf("\n Front -> %d ",front);
    64. printf("\n Items -> ");
    65. for( i = front; i!=rear; i=(i+1)%SIZE) {
    66. printf("%d ",items[i]);
    67. }
    68. printf("%d ",items[i]);
    69. printf("\n Rear -> %d \n",rear);
    70. }
    71. }
    72.  
    73. int main()
    74. {
    75. // Fails because front = -1
    76. deQueue();
    77.  
    78. enQueue(1);
    79. enQueue(2);
    80. enQueue(3);
    81. enQueue(4);
    82. enQueue(5);
    83.  
    84. // Fails to enqueue because front == 0 && rear == SIZE - 1
    85. enQueue(6);
    86.  
    87. display();
    88. deQueue();
    89.  
    90. display();
    91.  
    92. enQueue(7);
    93. display();
    94.  
    95. // Fails to enqueue because front == rear + 1
    96. enQueue(8);
    97.  
    98. return 0;
    99. }