Monday 6 February 2017

Use Queue data structure to print binary numbers from 1 to n: C Program

Use Queue data structure to print binary numbers from 1 to n.
1)       Create an empty queue of strings
2)       Enqueue the first binary number “1” to queue.
3)       Now run a loop for generating and printing n  Binary Numbers.
a) Dequeue and Print the front of queue.
b) Append “0” at the end of front item and enqueue it.
c) Append “1” at the end of front item and enqueue it.

Input: n=5
Output: 1,10,11,100,101

Program:
#include <stdio.h>
#include <string.h>
#define MAX 20
char queue[MAX][MAX], temp[MAX];
int front=-1, rear=-1;
void enq(char *s)
{
if(rear == MAX-1)
{
printf("Queye full");
return;
}
if(front == -1 && rear == -1)
front=rear=0;
else
rear=rear+1;
strcpy(queue[rear],s);
}
char* deq()
{
if(front == -1)
printf("stack is empty");
else
{
strcpy(temp,queue[front]);
if(front == rear)
front = rear = -1;
else
front=front+1;
return temp;
}
}
void bin()
{
char temp2[MAX];
strcpy(temp,deq());
printf("Binary numbers = %s\n",temp);
strcpy(temp2,temp);
strcat(temp,"0");
enq(temp);
strcat(temp2,"1");
enq(temp2);
}
main()
{
int i;
char temp[2]="1";
enq(temp);
for(i=1;i<=5;i++)
bin();

}


No comments:

Post a Comment