Showing posts with label FIFO. Show all posts
Showing posts with label FIFO. Show all posts

Sunday, November 29, 2026

Implementation of Queue Using Array in C – Data Structures Lab

 In this laboratory exercise, we design and implement a menu-driven C program to simulate the working of a Queue of integers using an array. The program demonstrates the fundamental queue operations: insertion, deletion and display.

The program is compatible with Code::Blocks on Windows.

1. Aim

Design, develop and execute a program in C to simulate the working of a Queue of integers using an array. Provide the following operations:

  • Insert (Enqueue)

  • Delete (Dequeue)

  • Display

2. Learning Objectives

After completing this laboratory exercise, students will be able to:

  • Understand the fundamental concepts of a Queue.

  • Understand the First In, First Out (FIFO) principle.

  • Implement a Queue using an array.

  • Perform insertion, deletion and display operations.

  • Understand Queue Overflow and Queue Underflow conditions.

  • Develop menu-driven programs in C.

  • Analyse the time and space complexity of queue operations.

3. Introduction

A Queue is a linear data structure in which elements are inserted at one end and removed from the other end.

A Queue follows the FIFO (First In, First Out) principle, which means that the element inserted first is the element removed first.

A real-life example of a Queue is a ticket booking counter, where the person who arrives first is served first.

FIFO principle: the first element inserted is the first element deleted.

Important Terminologies

Terminology

Description

Queue

Linear data structure following FIFO.

Front

Index of the first element in the Queue.

Rear

Index of the last element in the Queue.

Enqueue

Operation of inserting an element at the rear.

Dequeue

Operation of deleting an element from the front.

Overflow

Condition in which insertion is not possible because the rear has reached the array boundary.

Underflow

Condition in which deletion is attempted on an empty Queue.

4. Representation of Queue Using Array

A Queue can be implemented using a one-dimensional array and two integer variables, front and rear.

#define MAX 5

int queue[MAX];
int front = -1;
int rear = -1;

Initially, both front and rear are initialized to -1, indicating that the Queue is empty.

Consider a Queue with a maximum capacity of five elements.

Initially empty Queue

After inserting 10, 20 and 30

After deleting 10

5. Queue Operations

5.1 Insert Operation (Enqueue)

The Insert operation is used to add a new element at the rear end of the Queue.

Before inserting an element, the program checks whether the Queue can accommodate another element.

Overflow condition:

rear == MAX - 1

If the Queue is initially empty, front is initialized to zero.

The rear index is incremented, and the new element is stored at that position.

rear++;
queue[rear] = item;

For example, inserting 40 into a Queue containing 10, 20 and 30 results in:

Before insertion : 10 20 30
After insertion  : 10 20 30 40

5.2 Delete Operation (Dequeue)

The Delete operation removes an element from the front end of the Queue.

Before deleting an element, the program checks whether the Queue is empty.

Underflow condition:

front == -1

The element at the front is retrieved, and the front index is incremented.

item = queue[front];
front++;

If the last element is deleted, both front and rear are reset to -1.

For example:

Before deletion : 10 20 30 40
Deleted element : 10
After deletion  : 20 30 40

5.3 Display Operation

The Display operation displays all the elements currently present in the Queue.

The elements are traversed from the front index to the rear index.

for (i = front; i <= rear; i++)
{
    printf("%d ", queue[i]);
}

The Display operation does not modify the Queue.

6. Algorithm

Algorithm for Main Program

  1. Start.

  2. Declare an integer array of size MAX.

  3. Initialize front = -1 and rear = -1.

  4. Display the menu containing Insert, Delete, Display and Exit.

  5. Read the user's choice.

  6. Perform the corresponding operation using a switch statement.

  7. Repeat the operations until the user selects Exit.

  8. Stop.

Algorithm for Insert Operation

  1. Start.

  2. Check whether rear == MAX - 1.

  3. If true, display "Queue Overflow" and return.

  4. Read the element to be inserted.

  5. If front == -1, set front = 0.

  6. Increment rear by one.

  7. Store the element in queue[rear].

  8. Display the insertion confirmation.

  9. Stop.

Algorithm for Delete Operation

  1. Start.

  2. Check whether front == -1.

  3. If true, display "Queue Underflow" and return.

  4. Retrieve the element from queue[front].

  5. Display the deleted element.

  6. If front == rear, set both front and rear to -1.

  7. Otherwise, increment front by one.

  8. Stop.

Algorithm for Display Operation

  1. Start.

  2. Check whether front == -1.

  3. If true, display "Queue is Empty" and return.

  4. Initialize i = front.

  5. Display queue[i].

  6. Increment i by one.

  7. Repeat until i becomes greater than rear.

  8. Stop.

7. C Program

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

#define MAX 5

int queue[MAX];
int front = -1;
int rear = -1;

/* Function to insert an element into the Queue */

void insert()
{
    int item;

    /* Check for Queue Overflow */

    if (rear == MAX - 1)
    {
        printf("\nQueue Overflow!\n");
        return;
    }

    printf("Enter the element to insert: ");
    scanf("%d", &item);

    /* Check whether Queue is initially empty */

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

    rear++;
    queue[rear] = item;

    printf("%d inserted successfully.\n", item);
}

/* Function to delete an element from the Queue */

void delete()
{
    int item;

    /* Check for Queue Underflow */

    if (front == -1)
    {
        printf("\nQueue Underflow!\n");
        return;
    }

    item = queue[front];

    printf("Deleted element: %d\n", item);

    /* Check whether last element is deleted */

    if (front == rear)
    {
        front = -1;
        rear = -1;
    }
    else
    {
        front++;
    }
}

/* Function to display Queue elements */

void display()
{
    int i;

    /* Check whether Queue is empty */

    if (front == -1)
    {
        printf("\nQueue is Empty!\n");
        return;
    }

    printf("\nQueue Elements: ");

    for (i = front; i <= rear; i++)
    {
        printf("%d ", queue[i]);
    }

    printf("\nFront = %d", front);
    printf("\nRear  = %d\n", rear);
}

/* Main Function */

int main()
{
    int choice;

    while (1)
    {
        printf("\n----- QUEUE OPERATIONS -----\n");
        printf("1. Insert\n");
        printf("2. Delete\n");
        printf("3. Display\n");
        printf("4. Exit\n");

        printf("Enter your choice: ");
        scanf("%d", &choice);

        switch (choice)
        {
            case 1:
                insert();
                break;

            case 2:
                delete();
                break;

            case 3:
                display();
                break;

            case 4:
                printf("Exiting the program.\n");
                exit(0);

            default:
                printf("Invalid Choice!\n");
        }
    }

    return 0;
}

8. Program Execution Using Code::Blocks

  1. Open Code::Blocks.

  2. Select File → New → Project.

  3. Select Console Application.

  4. Select C as the programming language.

  5. Enter the project name as Queue_Using_Array.

  6. Select the destination folder.

  7. Open the main.c file.

  8. Replace the existing program with the above C program.

  9. Select Build and Run or press F9.

  10. Perform different Queue operations using the displayed menu.

Note: Save the program with the .c extension rather than .cpp, because delete is a reserved keyword in C++.

9. Sample Output

----- QUEUE OPERATIONS -----
1. Insert
2. Delete
3. Display
4. Exit
Enter your choice: 1
Enter the element to insert: 10
10 inserted successfully.

----- QUEUE OPERATIONS -----
1. Insert
2. Delete
3. Display
4. Exit
Enter your choice: 1
Enter the element to insert: 20
20 inserted successfully.

----- QUEUE OPERATIONS -----
1. Insert
2. Delete
3. Display
4. Exit
Enter your choice: 1
Enter the element to insert: 30
30 inserted successfully.

----- QUEUE OPERATIONS -----
1. Insert
2. Delete
3. Display
4. Exit
Enter your choice: 3

Queue Elements: 10 20 30
Front = 0
Rear  = 2

----- QUEUE OPERATIONS -----
1. Insert
2. Delete
3. Display
4. Exit
Enter your choice: 2
Deleted element: 10

----- QUEUE OPERATIONS -----
1. Insert
2. Delete
3. Display
4. Exit
Enter your choice: 3

Queue Elements: 20 30
Front = 1
Rear  = 2

----- QUEUE OPERATIONS -----
1. Insert
2. Delete
3. Display
4. Exit
Enter your choice: 4
Exiting the program.

10. Interactive Queue Simulation

The following simulation demonstrates the working of a linear Queue with a maximum capacity of five elements.

Linear Queue

Capacity: 5
Front

-1

Rear

-1

Elements

0/5

InsertDelete
Display
Reset
Program output

Queue is initialized and empty.

11. Dry Run – Step-by-Step Explanation

Consider a Queue of size five.

Operation

Queue elements

Front

Rear

Initialize

Empty

-1

-1

Insert 10

10

0

0

Insert 20

10, 20

0

1

Insert 30

10, 20, 30

0

2

Delete

20, 30

1

2

Insert 40

20, 30, 40

1

3

Insert 50

20, 30, 40, 50

1

4

Insert 60

Overflow

1

4

Delete

30, 40, 50

2

4

Delete

40, 50

3

4

Delete

50

4

4

Delete

Empty

-1

-1

Delete

Underflow

-1

-1

Insert 70

70

0

0

Notice that insertion of 60 results in Queue Overflow even though the first array position is vacant. This is a limitation of the linear Queue implementation.

12. Explanation of Important Functions

Function / Variable

Description

insert()

Inserts an integer at the rear end of the Queue.

delete()

Removes an integer from the front end of the Queue.

display()

Displays all the elements present in the Queue.

front

Maintains the index of the first element.

rear

Maintains the index of the last element.

MAX

Defines the maximum capacity of the Queue.

exit(0)

Terminates the program successfully.

switch

Executes the operation selected by the user.

13. Queue Overflow and Queue Underflow

Queue Overflow

Queue Overflow occurs when an insertion operation is attempted after the rear index has reached the last position of the array.

Condition:

rear == MAX - 1

Queue Underflow

Queue Underflow occurs when a deletion operation is attempted on an empty Queue.

Condition:

front == -1

14. Complexity Analysis

Operation

Time complexity

Reason

Insert

O(1)

Inserts an element directly at the rear index.

Delete

O(1)

Removes an element directly from the front index.

Display

O(n)

Traverses all active elements in the Queue.

Check Overflow

O(1)

Requires a single comparison.

Check Underflow

O(1)

Requires a single comparison.

Space Complexity: O(MAX)

The array allocates memory for MAX integer elements irrespective of the number of elements currently stored. Apart from the array, the operations require only constant auxiliary space, O(1).

Here, n represents the number of active elements in the Queue.

15. Difference Between Stack and Queue

Parameter

Stack

Queue

Principle

LIFO

FIFO

Insertion operation

Push

Enqueue

Deletion operation

Pop

Dequeue

Insertion position

Top

Rear

Deletion position

Top

Front

Variables required

Top

Front and Rear

Real-life example

Stack of plates

Ticket booking counter

Applications

Recursion, expression evaluation

Scheduling, buffering

Stack – LIFO

Last inserted is first deleted.

Queue – FIFO

First inserted is first deleted.

16. Types of Queues

Linear Queue

Insertion takes place at the rear, and deletion takes place at the front.

Circular Queue

The last array position is logically connected to the first position, allowing vacant spaces to be reused.

Priority Queue

Elements are removed according to their assigned priority rather than strictly following FIFO.

Double-Ended Queue (Deque)

Insertion and deletion operations can be performed at both ends of the Queue.

17. Applications of Queue Data Structure

Application

Usage of Queue

CPU Scheduling

Managing processes waiting for execution, such as in FCFS scheduling.

Printer Spooling

Maintaining print jobs awaiting printing.

Computer Networks

Buffering and managing data packets.

Breadth-First Search (BFS)

Traversing graphs level by level.

Level Order Traversal

Traversing nodes of a tree level by level.

Customer Support Systems

Managing customer requests.

Web Servers

Managing incoming requests.

Message Queues

Asynchronous communication between applications.

Keyboard Buffer

Temporarily storing keyboard input.

Ticket Reservation Systems

Managing sequential booking requests.

Event Handling

Processing events awaiting execution.

Operating Systems

Managing I/O requests and waiting processes.

18. Additional Test Cases

Test case

Operation

Expected result

1

Display an empty Queue

Queue is Empty

2

Delete from an empty Queue

Queue Underflow

3

Insert 10, 20, 30

Elements inserted successfully

4

Display

10, 20, 30

5

Delete

10 is deleted

6

Display

20, 30

7

Insert 40, 50

Elements inserted successfully

8

Insert 60

Queue Overflow

9

Delete all remaining elements

Queue becomes empty

10

Insert 70

Queue is reused successfully

11

Insert a negative integer

Negative integer inserted successfully, if space is available

12

Enter choice 9

Invalid Choice

19. Limitations of Linear Queue

The major limitation of a linear Queue implemented using an array is inefficient utilization of memory when elements are deleted.

Consider the following situation:

Although the first two positions are vacant, a new element cannot be inserted because rear has reached MAX - 1.

This condition is commonly referred to as False Overflow or wasted-space problem in a linear Queue.

This limitation can be overcome using a Circular Queue, where the rear index can wrap around to the beginning of the array.

Other limitations of the program include fixed storage capacity and the assumption that users enter valid integer inputs. Complete input validation is not implemented.

20. Extended Laboratory Exercises

For postgraduate students, the following modifications can be considered as additional programming exercises:

  1. Implement a Circular Queue using an array.

  2. Implement a Queue using a linked list.

  3. Implement a Priority Queue.

  4. Implement a Double-Ended Queue.

  5. Add a Peek operation to display the front element without deleting it.

  6. Implement a function to count the number of elements in the Queue.

  7. Implement isEmpty() and isFull() functions.

  8. Implement a Queue using two stacks.

  9. Simulate a printer scheduling system using a Queue.

  10. Simulate First Come, First Served (FCFS) CPU scheduling using a Queue.

  11. Implement a Queue using dynamically allocated memory.

  12. Modify the program to validate non-integer user inputs.

21. Viva Voce Questions

No.

Question

1

What is a Queue data structure?

2

What is the FIFO principle?

3

What is an Enqueue operation?

4

What is a Dequeue operation?

5

What is the purpose of front and rear variables?

6

Why are front and rear initialized to -1?

7

What is Queue Overflow?

8

What is Queue Underflow?

9

What is False Overflow?

10

Differentiate between Stack and Queue.

11

What are the different types of Queues?

12

What is a Circular Queue?

13

How does a Circular Queue overcome the limitation of a Linear Queue?

14

What is a Priority Queue?

15

What is a Double-Ended Queue?

16

What is the time complexity of insertion in a Queue?

17

What is the time complexity of deletion in a Queue?

18

Can a Queue be implemented using a linked list?

19

Which graph traversal algorithm uses a Queue?

20

How is a Queue used in CPU scheduling?

21

Why are front and rear reset after deleting the last element?

22

How do you calculate the number of elements in a non-empty Linear Queue?

23

Can a Queue be implemented using two stacks?

24

What is the difference between Peek and Dequeue?

25

What are the advantages and disadvantages of array-based Queue implementation?

22. Result

Thus, a menu-driven C program to simulate the working of a Queue of integers using an array has been designed and implemented. The expected behaviour of Insert, Delete and Display operations, along with Queue Overflow and Queue Underflow conditions, has been illustrated using suitable test cases.