## Introduction

A Queue is a First-In-First-Out (FIFO) data structure, which means that the first element added to the queue is the first one withdrawn. As a result, when a new element is added to the queue, all previous elements must be removed before the new element may be removed.

In this blog, we will discuss a popular problem and solve it using the queue __Data Structure____.__

### Problem Statement

Ninja has given you a number n, Your task is to print all the binary numbers ranging from 1 to n.

### Sample Examples

**Input**

**Output**

**Explanation**

## Approach

A simple approach would be to run a loop from 1 to n, and call the function decimal to binary inside the loop to convert all the numbers. We wonâ€™t be using this approach instead we will be using a queue data structure to solve the problem. The algorithm is explained below which will give us a clear idea about the approach.

### Algorithm

- Start
- Create an empty queue.
- Insert the first binary number(i.e. â€ś1â€ť) into the queue.
- Get the front element from the queue and print it on the screen. Remove this element from the queue.
- Add â€ś0â€ť at the end of the front element of the queue and insert it back into the queue.
- Add â€ś1â€ť at the end of the front element of the queue and insert it into the queue.
- Repeat steps 4, 5, and 6 â€śn â€ť times.
- Exit

### Implementation in Java

```
import java.util.LinkedList;
import java.util.Queue;
import java.util.Scanner;
public class CodingNinja {
// function to print binary numbers from 1 to n,
static void genBinary(int n) {
// creating an empty queue
Queue<String> queue = new LinkedList<String>();
// Enqueuing the first binary number into our queue
queue.add("1");
// loop to generate and print binary numbers from 1 to n;
while (n-- > 0) {
// printing the front element from the queue
String c1 = queue.peek();
queue.remove();
System.out.println(c1);
// Storing c1
String c2 = c1;
// Appending 0 to c1 and enqueuing it into our queue.
queue.add(c1 + "0");
// Appending 1 to c2 and enqueuing it into our queue.
queue.add(c2 + "1");
}
}
// main method
public static void main(String[] args) {
// getting the value of n from user
System.out.print("Enter the value of n: ");
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
// calling our function
genBinary(n);
}
}
```

**Input**

`Enter the value of n: 5`

**Output**

```
1
10
11
100
101
```

**Time Complexity**

The time complexity of the above program is O(n) as we have to generate the binary numbers up to n.

**Space Complexity**

We are using a queue data structure in this approach. So, the space complexity of the above program is O(n).

Must read __decimal to binary c++____,__ __Strong number in c__

Read about __Application of Queue__ in Data Structure here.