c code for queue using array

  • carray_queue
  • write a c code for queue using array

    Write a menu-driven program to implement queue operations such as Enqueue, Dequeue, Peek, Display of elements, Is Empty, and IsFull using a static array.

    Code

    #include <stdio.h> #include <stdlib.h> struct queue { int size; int f; int r; int *arr; }; int isEmpty(struct queue q) { if (q->r == q->f) { return 1; } return 0; } int isFull(struct queue *q) { if (q->r == q->size - 1) { return 1; } return 0; } void enqueue(struct queue *q, int val) { if (isFull(q)) { printf("This Queue is full\n"); } else { q->r++; q->arr[q->r] = val; printf("Enqued element: %d\n", val); } } int dequeue(struct queue *q) { int a = -1; if (isEmpty(q)) { printf("This Queue is empty\n"); } else { q->f++; a = q->arr[q->f]; } return a; } int peekF(struct queue *q) { return q->arr[q->f]; } int peekR(struct queue *q) { return q->arr[q->r]; } void display(struct queue *q) { int k = q->f + 1; while (k != q->r) { printf("%d ", q->arr[k]); k++; } printf("%d ", q->arr[k]); } int main() { struct queue q; int s; printf("enter the size of queue : "); scanf("%d", &s); q.size = s; q.f = q.r = 0; q.arr = (int *)malloc(q.size * sizeof(int)); int c, i; while (1) { options: printf("\n1.enqueue\n"); printf("2.dequeue\n"); printf("3.Display element at the front\n"); printf("4.Display element at the rear\n"); printf("5.Display all elements of the queue\n"); printf("6.isFull\n"); printf("7.isEmpty\n"); printf("8.Quit\n"); printf("\nEnter your choice : "); scanf("%d", &c); switch (c) { case 1: printf("\nInput the element for adding in queue : "); scanf("%d", &i); enqueue(&q, i); break; case 2: i = dequeue(&q); printf("\nDeleted element is %d\n", i); break; case 3: printf("\nElement at the front is %d\n", peekF(&q)); break; case 4: printf("\nElement at the rear is %d\n", peekR(&q)); break; case 5: display(&q); break; case 6: if (isFull(&q)) { printf("Queue is full\n"); } else { printf("Queue is not full\n"); } break; case 7: if (isEmpty(&q)) { printf("Queue is empty\n"); } else { printf("Queue is not empty\n"); } break; case 8: exit(1); default: printf("\nWrong choice\n"); } } return 0; }