0% found this document useful (0 votes)
1 views2 pages

Queue Using Array

Uploaded by

anshu5415341
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
1 views2 pages

Queue Using Array

Uploaded by

anshu5415341
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

with commennted explanation

front(for deletion)
rear(for insertion)

#include <stdio.h>
#include <stdlib.h>

#define SIZE 100 // Maximum size of queue (array capacity)

int queue[SIZE]; // Array to store queue elements


int front = -1; // Index of first element (-1 means empty)
int rear = -1; // Index of last element (-1 means empty)

/**
* Enqueue - Adds element to REAR (end) of queue - FIFO principle
* @param value: element to insert
*/
void enqueue(int value)
{
// Check if queue is FULL (rear reached last index)
if (rear == SIZE - 1)
{
printf("Queue Overflow! Cannot insert %d\n", value);
return;
}

// If queue was empty, set front to start (0)


if (front == -1)
front = 0;

rear++; // Move rear pointer forward (insertion point) front


queue[rear] = value; // Insert at rear position
printf("%d inserted into queue\n", value);
}

/** deleting
rear

* Dequeue - Removes element from FRONT (beginning) of queue


*/
void dequeue()
{
rear
// Check if queue is EMPTY: two cases front

// 1. Never used (front=-1) OR 2. All elements deleted (front > rear)


if (front == -1 || front > rear)
{
printf("Queue Underflow! Queue is empty\n");
return;
}

printf("%d deleted from queue\n", queue[front]); // Show element being removed


front++; // Move front forward (logically removes element)
// If no elements left, reset queue to initial empty state
if (front > rear)
front = rear = -1;
}

/**
* Display - Shows elements from front to rear
*/
void display()
{
if (front == -1) // Queue empty check
{
printf("Queue is empty\n");
return;
}

printf("Queue elements: ");


// Print valid elements only (front to rear)
for (int i = front; i <= rear; i++)
{
printf("%d ", queue[i]);
}
printf("\n");
}

int main()
{
// Demo: Insert 3 elements
enqueue(10); // front=0, rear=0: [10]
enqueue(20); // front=0, rear=1: [10,20]
enqueue(30); // front=0, rear=2: [10,20,30]

display(); // Prints: 10 20 30

dequeue(); // Removes 10, front=1: [20,30]


display(); // Prints: 20 30

return 0;
}

Download ready - Fully commented, production-quality linear queue implementation!

You might also like