How to utilize a queue to print binary numbers in Python

A queue is a data structure that is based on the FIFO (first in, first out) principle. Items that are appended to the queue are also removed in that same order.

Think of an actual queue formed when people wait in line for something. People who join the queue first also get their turn first. The data structure queue operates in the same manner.

How do you use a queue to print binary numbers

A queue can be utilized to print binary numbers using the following algorithm:

  1. Enqueue the first binary number 1 to the queue.

  2. While the desired number of binary numbers have not been printed:

    1. Dequeue an item from the queue.

    2. Print the dequeued item.

    3. Append 0 to the dequeued item, and enqueue the resulting string back to the queue.

    4. Append 1 to the dequeued item, and enqueue the resulting string back to the queue.

Note:

  • Each dequeued item is used to generate two new binary numbers.

  • We implement the numbers we are printing as strings, which allows appending 0 and 1 to the dequeued number.

Code example: Print binary numbers

Let’s implement the algorithm discussed in Python in the following manner.

Click the “Run” button to execute the code example:

import queue
def print_binary(num):
# creating a queue
q = queue.Queue()
# enqueuing the first binary number
q.put('1')
while(num > 0):
# Dequeuing and printing item
item = q.get()
print(item)
# enqueueing two more numbers
q.put(item + '0')
q.put(item + '1')
num = num - 1
if __name__ == "__main__":
print_binary(10)

Code explanation

Let's breakdown the code given above:

  • Lines 3–19: We implement a function print_binary that takes as input num, which dictates how many binary numbers should be printed:

    • Line 5: We create a queue q which is utilized to print the queue.

    • Line 8: We enqueue the first binary number.

    • Lines 10–19: We implement a loop which dequeues an item from the queue, prints it, and appends '0' and '1' to it respectively.

  • Lines 21–22: We implement the main function which calls the print_binary function.

Note: You can modify the number passed to print_binary on line 22 to observe how the printed binary numbers change.

Conclusion

Queues, adhering to the FIFO principle, are versatile data structures. The code example of printing binary numbers highlights how queues can be applied to generate sequences, emphasizing their importance in programming and algorithms.

Free Resources

Copyright ©2025 Educative, Inc. All rights reserved