C Program to Implement Queue using Array - GeeksforGeeks (2024)

Last Updated : 27 May, 2024

Improve

A queue is a linear data structure that follows the First-In-First-Out (FIFO) principle which means the elements added first in a queue will be removed first from the queue. In this article, we will learn how to implement a Queue using Array in C.

Implement Queue using Array in C

To implement Queue using Array in C, we can follow the below approach:

Approach:

  • Define a structure consisting of an array and two pointers front and rear.
  • Initialize the array with MAX_SIZE.
  • Initialize both the front and rear pointers to -1.
  • The insertion of elements will take place through the rear pointer and the deletion of elements will take place through the front pointer.
  • Implement isFull, isEmpty, Enqueue, and Dequeue functions to manipulate the elements of the queue easily.

Representation of Queue in C

The queue will be represented as a structure of fixed size array which consists of two pointers front and rear. The fixed size array will store the elements of the queue and the front and rear pointers will help the users to manipulate the queue elements.

struct Queue {
int queue[MAX_SIZE];
int front;
int rear;
};

The user can define the maximum size of the array as per their requirements and a utility function can be used to initialize the front and the rear pointers to -1.

Basic Operations of Queue

Following are the basic operations of the Queue data structure which are required to manipulate the elements present inside the Queue.

Operation

Description

Time Complexity

Space Complexity

Enqueue

Inserts an element at the end of the queue using the rear pointer.

O(1)

O(1)

Dequeue

Deletes an element from the front of the queue using the front pointer.

O(1)

O(1)

IsEmpty

Checks if the queue is empty or not. If front ==-1 returns true.

O(1)

O(1)

IsFull

Checks if the queue is full or not . If rear==MAX_SIZE-1 returns true.

O(1)

O(1)

Now let’s see how we can implement the basic functions of queue in C:

1. Enqueue Function

The enqueue function will insert an element at the end of the queue using the rear pointer. Following is the algorithm for enqueue function:

Algorithm for Enqueue Function

1. Check if the queue is full

2. If the queue is empty, set front pointer to 0.

3. Increment rear pointer and add the element at the rear position in the queue array.

2. Dequeue Function

The dequeue function will delete an element from the front of the queue using the front pointer. Following is the algorithm for enqueue function:

Algorithm for Dequeue Function

  1. Check if the queue is empty.
  2. If not, store the data at the front position of the queue.
  3. If front pointer is equal to rear, reset both pointers to -1, indicating an empty queue.
  4. Otherwise, increment the front pointer to point to the next element.

3. IsEmpty Function

The isEmpty function returns true if the queue is empty otherwise it returns false. Following is the algorithm for the isEmpty function:

Algorithm for IsEmpty Function

  1. Check if front pointer is equal to -1
  2. Return true if front==-1 .
  3. Return false if front!=-1.

4. IsFull Function

The isFull function returns true if the queue is full otherwise it returns false.The queue is full when the rear pointer points to the last index of the array. Following is the algorithm for the isFull function:

Algorithm for IsFull Function

  1. Check if rear pointer is equal to MAX_SIZE – 1.
  2. Return true if rear==MAX_SIZE -1 .
  3. Return false if rear != MAX_SIZE-1.

C Program to Implement Queue using Array

The following program illustrates how we can implement the queue data structure using arrays in C:

C
// C Program to implement queue using arrays#include <stdio.h>// Define the maximum size for the queue#define MAX_SIZE 100// Define a structure for the queuestruct Queue { int queue[MAX_SIZE]; int front; int rear;};// Function to initialize the queuevoid initializeQueue(struct Queue *q) { q->front = -1; q->rear = -1;}// Function to check if the queue is emptyint isEmpty(struct Queue *q) { return (q->front == -1);}// Function to check if the queue is fullint isFull(struct Queue *q) { return (q->rear == MAX_SIZE - 1);}// Function to insert an element into the queuevoid enqueue(struct Queue *q, int data) { if (isFull(q)) { printf("Queue is full\n"); return; } if (isEmpty(q)) { q->front = 0; } q->rear++; q->queue[q->rear] = data; printf("Enqueued %d in queue\n", data);}// Function to remove an element from the queueint dequeue(struct Queue *q) { if (isEmpty(q)) { printf("Queue is empty\n"); return -1; } int data = q->queue[q->front]; // If the queue is empty reset the pointers if (q->front == q->rear) { q->front = -1; q->rear = -1; } else { q->front++; } printf("Deleted element: %d\n", data); return data;}// Function to display the elements of the queuevoid display(struct Queue *q) { if (isEmpty(q)) { printf("Queue is empty\n"); return; } for (int i = q->front; i <= q->rear; i++) { printf("%d ", q->queue[i]); } printf("\n");}int main() { // Initialize a queue struct Queue q; initializeQueue(&q); enqueue(&q, 1); enqueue(&q, 2); enqueue(&q, 3); printf("Elements in the queue after enqueue operation: "); display(&q); dequeue(&q); printf("Elements in the queue after dequeue operation: "); display(&q); return 0;}

Output

Enqueued 1 in queueEnqueued 2 in queueEnqueued 3 in queueElements in the queue after enqueue operation: 1 2 3 Deleted element: 1Elements in the queue after dequeue operation: 2 3 

Applications of Queue

The queue data structure has various applications in different domains of computer science. Some of the applications are:

  • Queues are used in operating systems for process scheduling.
  • In printing systems Queues are used to maintain First In First Out(FIFO) order.
  • Queues are used in Graph data structures to perform Depth First Search(DFS).
  • Queues are used in databases for transaction processing.

Conclusion

In the following article we have learned about the queue data structure and how we can implement it using arrays in C. We have learnt about the basic operations which are required in a queue data structure to manipulate the elements of the queue. We have also learned about the various applications of queue data structure in the computer science domain.

Related Articles

These are some articles that you may want to read to improve your understanding about queue:

  • Queue Data Structure
  • Queue Using Linked List
  • Circular Queue
  • Priority Queue


S

sushantjarial

Improve

Next Article

C++ Program to Implement Queue using Array

Please Login to comment...

C Program to Implement Queue using Array - GeeksforGeeks (2024)

FAQs

How to make a queue using array in C? ›

Implement Queue using Array in C
  1. Define a structure consisting of an array and two pointers front and rear.
  2. Initialize the array with MAX_SIZE.
  3. Initialize both the front and rear pointers to -1.
May 27, 2024

How is a queue implemented in an array? ›

Queue implementation using Array:

For the implementation of queue, we need to initialize two pointers i.e. front and rear, we insert an element from the rear and remove the element from the front, and if we increment the rear and front pointer we may occur error, Due to which the front pointer may reach the end.

What is the queue in C geeksforgeeks? ›

A queue is a linear data structure that follows the First In First Out (FIFO) order of insertion and deletion. It means that the element that is inserted first will be the first one to be removed and the element that is inserted last will be removed at last.

How to implement a queue? ›

A queue can be implemented using Arrays, Linked-lists, Pointers, and Structures. The implementation using one-dimensional arrays is the easiest method of all the mentioned methods.

How to implement array in C? ›

To create an array, define the data type (like int ) and specify the name of the array followed by square brackets []. To insert values to it, use a comma-separated list, inside curly braces: int myNumbers[] = {25, 50, 75, 100}; We have now created a variable that holds an array of four integers.

Which array methods can be used to implement a queue? ›

A basic implementation of the queue data structure will be done with the methods:
  • enqueue() — Adds an element to the queue.
  • dequeue() — Removes and returns the first item entered in the queue.
  • isEmpty() — Returns true or false based on if the queue is empty or not.
  • front() — Returns the front element of the queue.
Mar 2, 2021

How to create a simple queue in C? ›

To implement a queue in C using an array, first define the queue's maximum size and declare an array of that size. The front and back integers were respectively set to 1. The front variable represents the front element of the queue, and the back variable represents the back element.

What is queue in C with example? ›

A queue in C is basically a linear data structure to store and manipulate the data elements. It follows the order of First In First Out (FIFO). In queues, the first element entered into the array is the first element to be removed from the array.

What are the four types of queue? ›

There are four types of queues in a data structure: linear queue, circular queue, priority queue, and de-queue. Linear Queue inserts from one end while deletes from the other. In a circular queue, all nodes are circular. It is identical to a linear queue, except the last member is connected to the first.

What are the three basic implementations of a queue? ›

There are three ways to implement Queues in Data Structures, using a 1D Array, a Single Linked List, and vectors.

What are the disadvantages of queue using array? ›

Drawbacks of Queue Implementation Using Array

This is because all the elements in the array need to be shifted to add the new front element. In the array implementation of a queue, memory is allocated for the maximum size of the queue, even if the queue is not full. This can result in inefficient use of memory.

What is the best data structure to implement a queue? ›

A priority queue can be implemented using a variety of data structures, such as a linked list, array, binary search tree, or heap. However, the heap is the most efficient data structure to implement a priority queue.

How to create Stack in C using array? ›

Step-by-step approach:
  1. Initialize an array to represent the stack.
  2. Use the end of the array to represent the top of the stack.
  3. Implement push (add to end), pop (remove from the end), and peek (check end) operations, ensuring to handle empty and full stack conditions.
Apr 15, 2024

How to add a row to an array in C? ›

Inserting a default object is the best way to insert an empty row into an array. For example, the following code inserts a blank row at the specified position: custtable. InsertRow(rownumber = row);

Can you have a queue of arrays? ›

- We can use an array of fixed capacity to store items as a queue. enqueue: append new items to the end of the queue • dequeue: remove items from the front of the queue, and shift the rest of the items.

Top Articles
US gas prices are falling. Experts point to mild demand at the pump ahead of summer travel
Opinion | Costco is the hero America needs right now
No Hard Feelings Showtimes Near Metropolitan Fiesta 5 Theatre
How To Fix Epson Printer Error Code 0x9e
Camera instructions (NEW)
Ymca Sammamish Class Schedule
Paris 2024: Kellie Harrington has 'no more mountains' as double Olympic champion retires
Boomerang Media Group: Quality Media Solutions
Unitedhealthcare Hwp
Coffman Memorial Union | U of M Bookstores
Rek Funerals
Undergraduate Programs | Webster Vienna
No Hard Feelings Showtimes Near Metropolitan Fiesta 5 Theatre
Sissy Hypno Gif
How To Get Free Credits On Smartjailmail
Naturalization Ceremonies Can I Pick Up Citizenship Certificate Before Ceremony
Orlando Arrest and Public Records | Florida.StateRecords.org
What Was D-Day Weegy
Summoners War Update Notes
Menards Eau Claire Weekly Ad
Homeaccess.stopandshop
Walmart Near South Lake Tahoe Ca
Evil Dead Rise Showtimes Near Pelican Cinemas
Drug Test 35765N
Zillow Group Stock Price | ZG Stock Quote, News, and History | Markets Insider
3 2Nd Ave
Amerisourcebergen Thoughtspot 2023
TJ Maxx‘s Top 12 Competitors: An Expert Analysis - Marketing Scoop
5 Star Rated Nail Salons Near Me
Allegheny Clinic Primary Care North
How often should you visit your Barber?
Siskiyou Co Craigslist
Salons Open Near Me Today
Song That Goes Yeah Yeah Yeah Yeah Sounds Like Mgmt
The Wichita Beacon from Wichita, Kansas
Appraisalport Com Dashboard /# Orders
Pitco Foods San Leandro
New York Rangers Hfboards
House Of Budz Michigan
SOC 100 ONL Syllabus
What Does Code 898 Mean On Irs Transcript
Craigslist Tulsa Ok Farm And Garden
Top 25 E-Commerce Companies Using FedEx
Henry Ford’s Greatest Achievements and Inventions - World History Edu
Directions To The Closest Auto Parts Store
The Wait Odotus 2021 Watch Online Free
Euro area international trade in goods surplus €21.2 bn
Mikayla Campinos Alive Or Dead
The Plug Las Vegas Dispensary
18443168434
Blippi Park Carlsbad
Códigos SWIFT/BIC para bancos de USA
Latest Posts
Article information

Author: Melvina Ondricka

Last Updated:

Views: 5281

Rating: 4.8 / 5 (68 voted)

Reviews: 91% of readers found this page helpful

Author information

Name: Melvina Ondricka

Birthday: 2000-12-23

Address: Suite 382 139 Shaniqua Locks, Paulaborough, UT 90498

Phone: +636383657021

Job: Dynamic Government Specialist

Hobby: Kite flying, Watching movies, Knitting, Model building, Reading, Wood carving, Paintball

Introduction: My name is Melvina Ondricka, I am a helpful, fancy, friendly, innocent, outstanding, courageous, thoughtful person who loves writing and wants to share my knowledge and understanding with you.