TechoSagar: Generate Binary Numbers

Search

Google Alert - jobs

Generate Binary Numbers

Given a number n, Write a program that generates and prints all binary numbers with decimal values from 1 to n.
Input:
The first line of input contains an integer T denoting the number of test cases.
The first line of each test case is N.

Output:
Print all binary numbers with decimal values from 1 to n in a single line.

Constraints:
1 ≤ T ≤ 100
1 ≤ N ≤ 500

Example:
Input
2
2
5
Output
1 10
1 10 11 100 101

 Your Code
#include<iostream>

using namespace std;

int main()
{
int t;
cin>>t;
while(t--)
{
int n;
cin>>n;
int i;
for(i=1; i<=n; i++)
{   int x=i;
   int k=0;
   int a[100],digit;
while(x!=0)
{
digit=x%2;
a[k]=digit;
//num++;
k++;
x=x/2;
   }
   int j;
   for(j=k-1; j>=0; j--)
   {
    cout<<a[j];
}
cout<<" ";
}
cout<<endl;
}
}

Follow us

Follow Bijendra Kumar on Facebook