Display Binary Numbers from 1 to N using Queue in C++

In this tutorial, we will learn how to write the program to display binary numbers using queue. Let us start with the algorithm to print Binary Numbers from 1 to N using Queue in C++.

Algorithm:

  1. Input the end value up to which the binary number has to be generated.
  2. Enqueue “1” to the queue.
  3. Initialize string t1= queue[front].
  4. Append “0” to string t1 and enqueue it to stack.
  5. Initialize string t2=queue[front].
  6. Append “1” to string t2 and enqueue it to the stack.
  7. Print queue [front] and dequeue it.
  8. Repeat step 3 to 7 until the end of the value.

In this program, we use the 3 functions. They are

  • insertion
  • deletion
  • generate

In Insertion function logic is if the front is equal to -1 then front equal to 0. In deletion function, if front equal to the rear then front and rear are equal to -1 else front is incremented by 1. In generate function we use string copy and string concatenation to copy the string and connect both the strings together.

Program: Display Binary Numbers from 1 to N using Queue in C++

#include<iostream>
#include<string.h>
# define maxsize 5
using namespace std;
int rear=-1;
int front =-1;
char queue [50][10];
void insertion(char * str)
{
rear=rear+1;
strcpy(queue[rear],str);
if(front==-1)
{
front =0;
}

}
void deletion()
{
if (front==rear)
{
front =rear =-1;
}
else
{
front++;
}
}
void generate(int n)
{
char t1[10],t2[10];
insertion("1");

int i=1;
for(i=1;i<=n;i++)
{
strcpy(t1,queue[front]);
strcat(t1,"0");
insertion(t1);
strcpy(t2,queue[front]);
strcat(t2,"1");
insertion(t2);
 cout<<queue[front]<<"\n";
 deletion();
}
}
int main()
{
int n=10;
generate (n);
return 0;

}

Output:

1
10
11
100
101
110
111
1000
1001
1010

Also, you can set your own range modifying this code.




Also, read:


Leave a Reply

Your email address will not be published. Required fields are marked *