Creating a Queue in C | DigitalOcean (2024)

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.

For example, let’s consider the scenario of a bus-ticket booking stall. Here, the fashion of a C programming queue is followed. The tickets are distributed on the first-come-first-serve basis i.e. the first one to enter is the first one to be served with the tickets.

A queue is open at both ends. One end is provided for the insertion of data and the other end for the deletion of data.

A queue can be implemented with any programming language such as C, Java, Python, etc.

Operations Associated with a Queue in C

A queue being an Abstract Data Structure provides the following operations for manipulation on the data elements:

  • isEmpty(): To check if the queue is empty
  • isFull(): To check whether the queue is full or not
  • dequeue(): Removes the element from the frontal side of the queue
  • enqueue(): It inserts elements to the end of the queue
  • Front: Pointer element responsible for fetching the first element from the queue
  • Rear: Pointer element responsible for fetching the last element from the queue

Working of Queue Data Structure

Queue follows the First-In-First-Out pattern. The first element is the first to be pulled out from the list of elements.

  • Front and Rear pointers keep the record of the first and last element in the queue.
  • At first, we need to initialize the queue by setting Front = -1 and Rear = -1
  • In order to insert the element (enqueue), we need to check whether the queue is already full i.e. check the condition for Overflow. If the queue is not full, we’ll have to increment the value of the Rear index by 1 and place the element at the position of the Rear pointer variable. When we get to insert the first element in the queue, we need to set the value of Front to 0.
  • In order to remove the element (dequeue) from the queue, we need to check whether the queue is already empty i.e. check the condition for Underflow. If the queue is not empty, we’ll have to remove and return the element at the position of the Front pointer, and then increment the Front index value by 1. When we get to remove the last element from the queue, we will have to set the values of the Front and Rear index to -1.

Implementation of Queue in C

Queues in C can be implemented using Arrays, Lists, Structures, etc. Below here we have implemented queues using Arrays in C.

Example:

#include <stdio.h># define SIZE 100void enqueue();void dequeue();void show();int inp_arr[SIZE];int Rear = - 1;int Front = - 1;main(){ int ch; while (1) { printf("1.Enqueue Operation\n"); printf("2.Dequeue Operation\n"); printf("3.Display the Queue\n"); printf("4.Exit\n"); printf("Enter your choice of operations : "); scanf("%d", &ch); switch (ch) { case 1: enqueue(); break; case 2: dequeue(); break; case 3: show(); break; case 4: exit(0); default: printf("Incorrect choice \n"); } } } void enqueue(){ int insert_item; if (Rear == SIZE - 1) printf("Overflow \n"); else { if (Front == - 1) Front = 0; printf("Element to be inserted in the Queue\n : "); scanf("%d", &insert_item); Rear = Rear + 1; inp_arr[Rear] = insert_item; }} void dequeue(){ if (Front == - 1 || Front > Rear) { printf("Underflow \n"); return ; } else { printf("Element deleted from the Queue: %d\n", inp_arr[Front]); Front = Front + 1; }} void show(){ if (Front == - 1) printf("Empty Queue \n"); else { printf("Queue: \n"); for (int i = Front; i <= Rear; i++) printf("%d ", inp_arr[i]); printf("\n"); }} 

Output:

1.Enqueue Operation2.Dequeue Operation3.Display the Queue4.ExitEnter your choice of operations : 1Element to be inserted in the Queue: 101.Enqueue Operation2.Dequeue Operation3.Display the Queue4.ExitEnter your choice of operations : 1Element to be inserted in the Queue: 201.Enqueue Operation2.Dequeue Operation3.Display the Queue4.ExitEnter your choice of operations : 3Queue: 10 20 1.Enqueue Operation2.Dequeue Operation3.Display the Queue4.ExitEnter your choice of operations : 2Element deleted from the Queue: 101.Enqueue Operation2.Dequeue Operation3.Display the Queue4.ExitEnter your choice of operations: 3Queue: 20 

Implementation of Queue using Stacks

Stack Data Structure can be used to implement the operations of the queue. We’ll need two stacks to implement a queue using them. Before you work through the examples below, make sure you understand the functioning of stacks very well.

A queue can be implemented using Stacks by either of the following ways:

  • Making the enqueue operation costly
  • Making the dequeue operation costly

Method 1: Making the enqueue Operation Costly

Let us assume two stacks: S1 and S2 to implement queue operations using the same.

  • If S1 is not empty, push all elements to stack 2 (S2)
  • In order to perform the enqueue operation, we will assume ‘x’ to be the element to be entered into the queue. We will push ‘x’ back to Stack S1 so it comes up on the top.
  • Further, push all the elements of stack S2 back to Stack S1

Note: The time complexity of the enqueue operation would be O(n).

  • In order to perform dequeue operation, we’ll need to pop an item from the Stack S1 since now the first inserted element is on the top in S1 instead of being at the bottom.

Note: The time complexity of the dequeue operation would be O(1).

If you analyze the time complexities of the Enqueue and Dequeue operations using Stack, you’ll find out that the Enqueue operation is much costlier than the Dequeue operation.

Thus, as mentioned above, we make the first entered or the oldest entered element to remain at the top of Stack S1 so that it gets removed when the Dequeue operation is invoked.

Method 2: Making the Dequeue operation costly

Let us again assume two Stacks: S1 and S2 to implement queue operations using the same.

  • In order to implement enqueue operation, we insert the newly entered element at the top of Stack S1. Thus, the time complexity of the Enqueue operation using Stacks becomes O(1).
  • For the implementation of dequeue operation, it checks for the Underflow condition of Stack S1 and S2. If both the Stacks stands out to be empty, an error would be raised.
  • If the Stack S2 is empty and S1 is not empty, then all the elements from Stack S1 are moved to Stack S2 and the top element of Stack S2 is popped out and returned out of the Dequeue operation.
  • Thus, the time complexity of the dequeue operation using Stacks becomes O(n).

Applications of Queue Data Structure

  • CPU Scheduling
  • Disk Scheduling
  • Asynchronous data transfer between processors such as File IO, etc.
  • Breadth-First Search Algorithm (BFS)

Conclusion

In this article, we have understood the working of queue data structure and have also shadowed over the implementation of queues using stack data structure.

References

Creating a Queue in C | DigitalOcean (2024)

FAQs

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.

Does C have a built-in queue? ›

In C, the queue can be represented as the structure that contains one array of fixed size, index pointer to the front, and index pointer to the end. The front pointer initial value will be -1 and the back pointer initial value will be 0.

How to insert queue in data structure in C? ›

Step for inserting an element in a Queue in C

Accept the data that we want to enter in a queue using a for loop. After accepting the data use enqueue() function to insert the data in a queue. In this function return queue id full , if the value of rear is equal to max-1. Else increase the value of rear by 1.

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

What is the easiest way 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.

What is the difference between a stack and a queue? ›

A Stack is a linear data structure where removal and insertion occur at the same end. A Queue is also a linear data structure, but removal and insertion happen at different ends. A Stack follows the Last In, First Out (LIFO) principle, meaning the most recently inserted element is removed first.

How to implement stack and queue in C? ›

C Program to Implement Queues using Stack
  1. Take the elements as input and store it in the stack array. Use this array to show the stack operations.
  2. Transfer the elements from the stack array into the new array. Do the queue operations in the new array.
  3. Exit.

What are the types of queue in C? ›

The queue data structure is a linear data structure used to hold items. In programming, a queue is an important data structure. Elements in this data structure are stored using the FIFO approach. There are four types of queues in a data structure: linear queue, circular queue, priority queue, and de-queue.

What is the difference between queue and list in C? ›

Queue is a collection of one or more elements arranged in memory in a contiguous fashion. A linked list is a collection of one or more elements arranged in memory in a dis-contiguous fashion. Static Queue is always fixed size. List size is never fixed.

What is a stack in C? ›

A stack in C refers to a linear data structure that allows the insertion of a new element and deletion of an existing element at the same end which is depicted as the top of the stack. For stack implementation, the pointer must be maintained at the top of the stack, i.e., the last element to be inserted in the stack.

How to sort a queue in C? ›

Sort the Queue using Recursion
  1. empty(q): Tests whether the queue is empty or not.
  2. push(q): Adds a new element to the queue.
  3. pop(q): Removes front element from the queue.
  4. size(q): Returns the number of elements in a queue.
  5. front(q): Returns the value of the front element without removing it.
Jan 5, 2023

Does C have a queue? ›

A queue is a linear data structure in the C language that adheres to the FIFO (First In, First Out) rule. Arrays or linked lists can be used to implement it statically or dynamically.

What is an example of a queue? ›

Let's consider a queue in data structure example. A line of people is waiting to buy a ticket at a cinema hall. A new person will join the line from the end, and the person standing at the front will be the first to get the ticket and leave the line.

What is a simple queue in data structure? ›

A simple queue is the most basic queue. In this queue, the enqueue operation takes place at the rear, while the dequeue operation takes place at the front: Its applications are process scheduling, disk scheduling, memory management, IO buffer, pipes, call center phone systems, and interrupt handling.

What is queue in C programming simplified? ›

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.

How to create a simple function in C? ›

The following is the syntax for defining a function in C: return_type function_name(parameter_list); Here, return_type is the data type of the value that the function returns. function_name is the name of the function, and parameter_list is the list of parameters that the function takes as input.

How to make a queue with two stacks in C? ›

The following algorithm will implement a queue using two stacks. (1) When calling the enqueue method, simply push the elements into the stack 1. (2) If the dequeue method is called, push all the elements from stack 1 into stack 2, which reverses the order of the elements. Now pop from stack 2.

How to make a simple program in C? ›

Begin your 1st C Program
  1. Open any text editor or IDE and create a new file with any name with a .C extension. e.g. helloworld.c.
  2. Open the file and enter the below code: #include <stdio.h> int main() { printf("Hello, World!" ); return 0; } Run Code >>
  3. Compile and run the code.
May 27, 2024

Top Articles
What are Subdomains? (Definition and Examples)
What's a Subdomain & How Is It Used?
Skigebiet Portillo - Skiurlaub - Skifahren - Testberichte
Trevor Goodwin Obituary St Cloud
Mcgeorge Academic Calendar
Hannaford Weekly Flyer Manchester Nh
Live Basketball Scores Flashscore
Cottonwood Vet Ottawa Ks
Txtvrfy Sheridan Wy
10000 Divided By 5
Weapons Storehouse Nyt Crossword
Call of Duty: NEXT Event Intel, How to Watch, and Tune In Rewards
Costco in Hawthorne (14501 Hindry Ave)
LeBron James comes out on fire, scores first 16 points for Cavaliers in Game 2 vs. Pacers
Jscc Jweb
Cranberry sauce, canned, sweetened, 1 slice (1/2" thick, approx 8 slices per can) - Health Encyclopedia
DIN 41612 - FCI - PDF Catalogs | Technical Documentation
Spelunking The Den Wow
Washington, D.C. - Capital, Founding, Monumental
Uhcs Patient Wallet
Think Up Elar Level 5 Answer Key Pdf
Aris Rachevsky Harvard
Www Craigslist Com Bakersfield
Azur Lane High Efficiency Combat Logistics Plan
Www.paystubportal.com/7-11 Login
Gas Buddy Prices Near Me Zip Code
Naval Academy Baseball Roster
Greyson Alexander Thorn
Danielle Ranslow Obituary
Soul Eater Resonance Wavelength Tier List
Random Bibleizer
Busted Mugshots Paducah Ky
Is Light Raid Hard
Bi State Schedule
Gyeon Jahee
Wattengel Funeral Home Meadow Drive
Marcus Roberts 1040 Answers
Infinite Campus Parent Portal Hall County
Karen Wilson Facebook
Weather Underground Cedar Rapids
Isabella Duan Ahn Stanford
11 Best Hotels in Cologne (Köln), Germany in 2024 - My Germany Vacation
Umd Men's Basketball Duluth
Ladyva Is She Married
Hkx File Compatibility Check Skyrim/Sse
Citroen | Skąd pobrać program do lexia diagbox?
Craigslist Com St Cloud Mn
Senior Houses For Sale Near Me
Reilly Auto Parts Store Hours
The Bold and the Beautiful
Is TinyZone TV Safe?
Sml Wikia
Latest Posts
Article information

Author: Fredrick Kertzmann

Last Updated:

Views: 5277

Rating: 4.6 / 5 (66 voted)

Reviews: 89% of readers found this page helpful

Author information

Name: Fredrick Kertzmann

Birthday: 2000-04-29

Address: Apt. 203 613 Huels Gateway, Ralphtown, LA 40204

Phone: +2135150832870

Job: Regional Design Producer

Hobby: Nordic skating, Lacemaking, Mountain biking, Rowing, Gardening, Water sports, role-playing games

Introduction: My name is Fredrick Kertzmann, I am a gleaming, encouraging, inexpensive, thankful, tender, quaint, precious person who loves writing and wants to share my knowledge and understanding with you.