0% found this document useful (0 votes)
6 views

Queue Report

Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views

Queue Report

Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 3

Generate binary numbers between 1 to n using a queue

For example, for n = 16, the binary numbers are:


1 10 11 100 101 110 111 1000 1001 1010 1011 1100 1101 1110 1111 10000

#include <stdio.h>
Code
#include <stdlib.h>
#include <stdbool.h>
int que_arr[101];
int max_size = 100;
int nElement = 0,front =-1,rear = 0;

bool que_isFull()
{
return nElement == max_size;
}
bool que_isEmpty()
{
return (nElement == 0) ;
}
void que_inque (int ele)
{
if(!que_isFull())
{
if(rear == max_size)
{
rear =0;
}
que_arr[rear++] = ele;
nElement++;
if(front == -1) front = 0; //move the front to be able to read the first element
}
else {printf("Queue OverFlow \n");}
}
int que_deque ()
{
if( !que_isEmpty())
{
int res= que_arr[front]; //dequeue the value
front ++; //delete the value
if(front == max_size)
{
front = 0;
}
nElement--;
return res;
}
else {printf("Queue UnderFlow \n");}
}
int que_peek()
{
return que_arr[front];
}
void Generate(int n)
{
que_inque (1);
// run n times
int i = 1;
while (i++ <= n)
{
// append 0 and 1 to the front element of the queue and
// inqueue both
que_inque (que_peek()*10+0);
que_inque (que_peek()*10+1);
// dequeue front element
printf("%d ",que_deque ());
}
}
int main()
{
int n;
printf("enter number:");
scanf("%d",&n);
printf("Generated binary numbers between 1 to %d is:\n",n);
Generate(n);
return 0;
}
Test cases
Case 1
enter number:16
Generated binary numbers between 1 to 16 is:
1 10 11 100 101 110 111 1000 1001 1010 1011 1100 1101 1110 1111
10000

Case 2
enter number:7
Generated binary numbers between 1 to 7 is:
1 10 11 100 101 110 111

Case 3
enter number:31
Generated binary numbers between 1 to 31 is:
1 10 11 100 101 110 111 1000 1001 1010 1011 1100 1101 1110 1111
10000 10001 10010 10011 10100 10101 10110 10111 11000 11001
11010 11011 11100 11101 11110 11111

You might also like