kebria

Implementing Queue in C. Using Array

Jun 23rd, 2021
649
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. /* Implementing Queue in C. Using Array */
  2. #include <stdio.h>
  3. #define CAPACITY 5
  4. int front = 0, rear = -1, totalitem = 0;
  5. int ourq[CAPACITY];
  6.  
  7. void enq(int item)
  8. {
  9.     if (totalitem == CAPACITY)
  10.     {
  11.         printf("Opps!!The queue is Full\n");
  12.         return;
  13.     }
  14.     else
  15.     {
  16.         rear = (rear + 1) % CAPACITY;
  17.         ourq[rear] = item;
  18.         totalitem++;
  19.     }
  20. }
  21.  
  22. int deq()
  23. {
  24.     if (totalitem == 0)
  25.     {
  26.         printf("Opps!!The queue is empty\n");
  27.         return -1;
  28.     }
  29.     else
  30.     {
  31.         int frontitem = ourq[front];
  32.         ourq[front] = -1;
  33.         front = (front + 1) % CAPACITY;
  34.         totalitem--;
  35.         return frontitem;
  36.     }
  37. }
  38.  
  39. void print()
  40. {
  41.     int i;
  42.     for (i = 0; i < CAPACITY; i++)
  43.     {
  44.         printf("%d ", ourq[i]);
  45.     }
  46.     printf("\n");
  47. }
  48.  
  49. int main()
  50. {
  51.     printf("Implementing Queue\n");
  52.     enq(10);
  53.     enq(20);
  54.     enq(30);
  55.     enq(40);
  56.     print();
  57.     enq(50);
  58.     print();
  59.     enq(60);
  60.     printf("Deq: %d\n", deq());
  61.     print();
  62.     enq(70);
  63.     print();
  64.  
  65.     return 0;
  66. }
  67.  
  68.  
  69. /*
  70. Output:
  71. Implementing Queue
  72. 10 20 30 40 0
  73. 10 20 30 40 50
  74. Opps!!The queue is Full
  75. Deq : 10
  76. - 1 20 30 40 50
  77. 70 20 30 40 50
  78. */
RAW Paste Data