
- C Programming Tutorial
- C - Home
- C - Overview
- C - Environment Setup
- C - Program Structure
- C - Basic Syntax
- C - Data Types
- C - Variables
- C - Constants
- C - Storage Classes
- C - Operators
- C - Decision Making
- C - Loops
- C - Functions
- C - Scope Rules
- C - Arrays
- C - Pointers
- C - Strings
- C - Structures
- C - Unions
- C - Bit Fields
- C - Typedef
- C - Input & Output
- C - File I/O
- C - Preprocessors
- C - Header Files
- C - Type Casting
- C - Error Handling
- C - Recursion
- C - Variable Arguments
- C - Memory Management
- C - Command Line Arguments
- C Programming useful Resources
- C - Questions & Answers
- C - Quick Guide
- C - Useful Resources
- C - Discussion
An Interesting Method to Generate Binary Numbers from 1 to n?
Here we will see one interesting method for generating binary numbers from 1 to n. Here we are using queue. Initially the queue will hold first binary number ‘1’. Now repeatedly delete element from queue, and print it, and append 0 at the end of the front item, and append 1 at the end of the front time, and insert them into the queue. Let us see the algorithm to get the idea.
Algorithm
genBinaryNumbers(n)
Begin define empty queue. insert 1 into the queue while n is not 0, do delete element from queue and store it into s1 print s1 s2 := s1 insert s1 by adding 0 after it into queue insert s1 by adding 1 after it into queue decrease n by 1 done End
Example
#include <iostream> #include <queue> using namespace std; void genBinaryNumbers(int n){ queue<string> qu; qu.push("1"); while(n != 0){ string s1 = qu.front(); qu.pop(); cout << s1 << " "; string s2 = s1; qu.push(s1 + "0"); qu.push(s1 + "1"); n--; } } int main() { int n = 15; genBinaryNumbers(n); }
Output
1 10 11 100 101 110 111 1000 1001 1010 1011 1100 1101 1110 1111
- Related Articles
- An interesting solution to get all prime numbers smaller than n?
- Program to find duplicate element from n+1 numbers ranging from 1 to n in Python
- 1 to n bit numbers with no consecutive 1s in binary representation?
- Java Program to generate n distinct random numbers
- Java Program to Display All Prime Numbers from 1 to N
- Swift Program to Display All Prime Numbers from 1 to N
- Haskell program to display all prime numbers from 1 to n
- Kotlin Program to Display All Prime Numbers from 1 to N
- JavaScript function to take a number n and generate an array with first n prime numbers
- Python Program to Generate Random Numbers from 1 to 20 and Append Them to the List
- 8086 program to generate AP series of n numbers
- 8086 program to generate G.P. series of n numbers
- Program to generate first n lexicographic numbers in python
- Print prime numbers from 1 to N in reverse order
- Find four missing numbers in an array containing elements from 1 to N in Python

Advertisements