What Is FIFO Data Structure Example?

//

Larry Thompson

The FIFO (First-In-First-Out) data structure is a fundamental concept in computer science that is widely used in various applications. It follows the principle of queuing, where the first element inserted is the first one to be removed. In this article, we will explore what FIFO is and provide a simple example to help you understand its functionality.

What is FIFO Data Structure?

FIFO is an abstract data type that represents a collection of elements arranged in a specific order. It operates on the principle of “first come, first served.” The element that enters the data structure first will be the first one to be processed or removed.

Example of FIFO Data Structure

Let’s consider a real-life scenario of people waiting in line to buy movie tickets. The person who arrives first gets their ticket first and goes inside the theater. Similarly, the second person in line gets their ticket next, and this continues until everyone has been served.

To implement this scenario using a FIFO data structure, we can use an array or a linked list. Let’s choose an array for simplicity.

Creating an Array for FIFO

We start by creating an empty array with a fixed size:

``` <script> let queue = []; const maxSize = 5; </script> ```

In this example, we set the maximum size of our queue to 5.

Enqueuing Elements

To enqueue or add elements to our queue, we can use the push() method:

``` <script> queue.push("Person 1"); queue.push("Person 2"); queue.push("Person 3"); </script> ```

We have now added three people to our queue.

Dequeuing Elements

To dequeue or remove elements from our queue, we can use the shift() method:

``` <script> let nextPerson = queue.shift(); document.write("The next person is: " + nextPerson); </script> ```

The output will be:

The next person is: Person 1

Now, the first person in line has been served, and we can continue dequeuing to serve the remaining people.

Checking Queue Size

If we want to check the current size of our queue, we can use the length property:

``` <script> let currentSize = queue.length; document.write("Current queue size: " + currentSize); </script> ```

The output will be:

Current queue size: 2

Conclusion

FIFO data structure follows a simple principle of processing elements in the order they enter. It is widely used in various applications, such as job scheduling, buffer management, and more. Understanding FIFO is crucial for building efficient algorithms and data structures.

In this article, we explored what FIFO data structure is and provided a simple example using an array. By implementing the enqueue and dequeue operations, we created a basic FIFO system for serving people waiting in line. Remember to apply this concept to your own projects to improve their efficiency!