Docsity

Implementing Queue Operations in C, Lecture notes of English Literature

Toggle sidebar
bg1
1 |BY SHIVANI SHARMA (220532)
ENQUEUE
#include <stdio.h>
int main() {
int max_size;
printf("Enter the maximum size of the queue: "); // Ask the max size of the queue
scanf("%d", &max_size);
int Q[max_size]; // Queue array
int rear = -1; // Set Rear
int isFull() { // checking if the queue is full
return rear == max_size - 1;
}
void enqueue(int item) { // Function to enqueue
if (isFull()) {
printf("Queue Overflow: Cannot enqueue %d\n", item);
} else {
rear++;
Q[rear] = item;
}
}
int num_elements, item; // Ask the user for the number of elements to enqueue
printf("Enter the number of elements you want to enqueue in this queue: ");
scanf("%d", &num_elements);
for (int i = 0; i < num_elements; i++) {
printf("Enter element %d: ", i + 1);
scanf("%d", &item);
enqueue(item);
}
printf("Queue elements: "); // Print the elements in the queue
for (int i = 0; i <= rear; i++) {
printf("%d ", Q[i]);
pf3
pf4
pf5

Partial preview of the text

Download Implementing Queue Operations in C and more Lecture notes English Literature in PDF only on Docsity!

ENQUEUE

#include <stdio.h> int main() { int max_size; printf("Enter the maximum size of the queue: "); // Ask the max size of the queue scanf("%d", &max_size); int Q[max_size]; // Queue array int rear = -1; // Set Rear int isFull() { // checking if the queue is full return rear == max_size - 1; } void enqueue(int item) { // Function to enqueue if (isFull()) { printf("Queue Overflow: Cannot enqueue %d\n", item); } else { rear++; Q[rear] = item; } } int num_elements, item; // Ask the user for the number of elements to enqueue printf("Enter the number of elements you want to enqueue in this queue: "); scanf("%d", &num_elements); for (int i = 0; i < num_elements; i++) { printf("Enter element %d: ", i + 1); scanf("%d", &item); enqueue(item); } printf("Queue elements: "); // Print the elements in the queue for (int i = 0; i <= rear; i++) { printf("%d ", Q[i]);

printf("\n"); return 0; }

printf("Element %d: ", i + 1); scanf("%d", &Q[i]); } front = 0; rear = num_elements - 1; dequeue(); // Dequeue the first element return 0; }

DISPLAY/TRAVERSE WHOLE QUEUE

#include <stdio.h> #define MAX_SIZE 7 // Maximum size of the queue int Q[MAX_SIZE]; int front = -1; int rear = -1; int isEmpty() { // checking if the queue is empty return front == -1 || front > rear; } int main() { // Enqueue specific elements into the queue(I’VE LET MY ELEMENTS IN MY CODE ONLY) Q[0] = 10; Q[1] = 20; Q[2] = 30; Q[3] = 40; Q[4] = 69; rear = 4; // Update the rear pointer accordingly printf("Queue elements: "); // Displaying/ traversing the queue for (int i = front; i <= rear; i++) { printf("%d ", Q[i]); } printf("\n"); return 0; }