Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Buy a domain name - Register cheap domain names from $0.99 - Namecheap

Scalable Hosting That Grows With You

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Semrush - keyword research tool

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

39,948 questions

51,890 answers

573 users

How to generate all the binary options of N bits in C++

2 Answers

0 votes
#include <iostream>
 
void printArray(int arr[], int N) {
    for (int i = 0; i < N; i++) {
        std::cout << arr[i] << " ";
    }
    std::cout << "\n";
}
  
void generateAllBinaryOptions(int arr[], int N, int i) {
    if (i == N) {
        printArray(arr, N);
        return;
    }
    arr[i] = 0;
    generateAllBinaryOptions(arr, N, i + 1);
  
    arr[i] = 1;
    generateAllBinaryOptions(arr, N, i + 1);
}

int main()
{
    int N = 4;
  
    int arr[32];
  
    generateAllBinaryOptions(arr, N, 0);
}
 
 
 
 
 
/*
run:
 
0 0 0 0 
0 0 0 1 
0 0 1 0 
0 0 1 1 
0 1 0 0 
0 1 0 1 
0 1 1 0 
0 1 1 1 
1 0 0 0 
1 0 0 1 
1 0 1 0 
1 0 1 1 
1 1 0 0 
1 1 0 1 
1 1 1 0 
1 1 1 1 
 
*/

 



answered Aug 25, 2023 by avibootz
edited Aug 25, 2023 by avibootz
0 votes
#include <iostream>
#include <bitset>
 
void generateAllBinaryOptions(int N) {
    int total_bits = 1 << N; // = 2 ^ N
    
    for (int i = 0; i < total_bits; i++) {
        std::bitset<32> bs(i);
        std::cout << bs.to_string().substr(32 - N) << "\n";
    }
}
  
int main()
{
    int N = 4;
  
    generateAllBinaryOptions(N);
}
 
 
 
 
 
/*
run:
 
0000
0001
0010
0011
0100
0101
0110
0111
1000
1001
1010
1011
1100
1101
1110
1111
 
*/

 



answered Aug 25, 2023 by avibootz
edited Aug 25, 2023 by avibootz

Related questions

1 answer 106 views
1 answer 98 views
1 answer 106 views
1 answer 102 views
1 answer 93 views
1 answer 100 views
1 answer 112 views
...