(DSL5) Normal Queue Operations
🚶

(DSL5) Normal Queue Operations

Code

#include <stdio.h> #include <stdlib.h> #define MAX 10 typedef struct { int * arr[MAX]; int front; int rear; } Queue; void main() { int choice, num, i; Queue queue; Queue *ptr = &queue; init(ptr); printf("Enter the number of elements: "); scanf("%d", &num); printf("Enter the elements: \n"); for (i = 0; i < num; i++) { scanf("%d", &ptr->arr[i]); } (*ptr).front = 0; (*ptr).rear = num - 1; while (1) { printf("\n--- QUEUE OPERATIONS ---"); printf("\n 1. Enqueue Element"); printf("\n 2. Dequeue Element"); printf("\n 3. Display Elements"); printf("\n 4. Exit."); printf("\n\n Enter your choice: "); scanf("%d", &choice); switch (choice) { case 1: if (isFull(ptr)) printf(" Queue is full! \n"); else enqueue(ptr); break; case 2: if (isEmpty(ptr)) printf(" Queue is empty! \n"); else dequeue(ptr); break; case 3: display(ptr); break; case 4: exit(0); default: printf("\n Wrong choice! \n"); } } } void init(Queue *ptr) { ptr->front = -1; ptr->rear = -1; } int isFull(Queue *ptr) { return ((*ptr).rear == MAX - 1); } int isEmpty(Queue *ptr) { return ((*ptr).front > (*ptr).rear); } void enqueue(Queue *ptr) { int ele; printf(" Enter the element: "); scanf("%d", &ele); (*ptr).arr[(ptr->rear)+1] = ele; (*ptr).rear += 1; display(ptr); } void dequeue(Queue *ptr) { printf("Element (%d) removed from index %d!", ptr->arr[ptr->front], ptr->front); (*ptr).front += 1; display(ptr); } void display(Queue *ptr) { int i; printf("\n Queue is: \n "); for (i = ptr->front; i <= ptr->rear; i++) { printf("%d, ", ptr->arr[i]); } printf("\n Front is: %d", ptr->front); printf("\n Back is: %d\n", ptr->rear); }

Output

(For observation only. You can shorten this down as required.)
Enter the number of elements: 9 Enter the elements: 1 2 3 4 5 6 7 8 9 --- QUEUE OPERATIONS --- 1. Enqueue Element 2. Dequeue Element 3. Display Elements 4. Exit. Enter your choice: 1 Enter the element: 10 Queue is: 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, Front is: 0 Back is: 9 --- QUEUE OPERATIONS --- 1. Enqueue Element 2. Dequeue Element 3. Display Elements 4. Exit. Enter your choice: 1 Queue is full! --- QUEUE OPERATIONS --- 1. Enqueue Element 2. Dequeue Element 3. Display Elements 4. Exit. Enter your choice: 2 Element (1) removed from index 0! Queue is: 2, 3, 4, 5, 6, 7, 8, 9, 10, Front is: 1 Back is: 9 --- QUEUE OPERATIONS --- 1. Enqueue Element 2. Dequeue Element 3. Display Elements 4. Exit. Enter your choice: 2 Element (2) removed from index 1! Queue is: 3, 4, 5, 6, 7, 8, 9, 10, Front is: 2 Back is: 9 --- QUEUE OPERATIONS --- 1. Enqueue Element 2. Dequeue Element 3. Display Elements 4. Exit. Enter your choice: 3 Queue is: 3, 4, 5, 6, 7, 8, 9, 10, Front is: 2 Back is: 9 --- QUEUE OPERATIONS --- 1. Enqueue Element 2. Dequeue Element 3. Display Elements 4. Exit. Enter your choice: 4 Process returned 0 (0x0) execution time : 16.432 s Press any key to continue.