Monday 14 October 2024

Write a program to implement the queue

 #include <stdio.h>

#define SIZE 5


int queue[SIZE], front = -1, rear = -1;


void enqueue(int value) {

    if (rear == SIZE - 1)

        printf("Queue is full!\n");

    else {

        if (front == -1)

            front = 0;

        rear++;

        queue[rear] = value;

        printf("Inserted %d\n", value);

    }

}


/*

1.Checking if the Queue is Full:

if (rear == SIZE - 1)

The rear index tracks the position of the last inserted element in the queue.

If rear is equal to SIZE - 1, it means the queue has reached its maximum capacity (SIZE is the total size of the queue).


2.if (front == -1)

    front = 0;

If front is -1, it means the queue is currently empty. Setting front to 0 .


3.rear++

rear is -1, so the first element is inserted at position 0, and the index keeps increasing as new elements are enqueued.


*/



void dequeue() {

    if (front == -1)

        printf("Queue is empty!\n");

    else {

  printf("Deleted %d\n", queue[front]);

        front++;

    }

}




void display() {

    if (front == -1)

        printf("Queue is empty!\n");

    else {

        printf("Queue elements are: ");

        for (int i = front; i <= rear; i++)

            printf("%d ", queue[i]);

        printf("\n");

    }

}



/*The loop variable i starts at front (the index of the first element) and goes up to rear (the index of the last element).*/



int main() {

    enqueue(10);

    enqueue(20);

    enqueue(30);

    dequeue();

    display();

    return 0;

}