How to output all possible binary combinations?

Hello,

I need to create a function that outputs all possible binary combinations. I'm really stumped on this. I have to do it with nested loops, and am not sure how to go about it. Below is what I tried so far.

The output should look like this:

00000000
00000001
00000010
00000011
00000100
...
11111110
11111111

Thanks for looking.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49

void outputBinary(){

int a[2][2][2][2][2][2][2][2];

for (int i = 0; i < 2; i++){

for (int j = 0; j < 2; j++){

for (int k = 0; k < 2; k++){

for (int l = 0; l < 2; l++){

for (int m = 0; m < 2; m++){

for (int n = 0; n < 2; n++){

for (int o = 0; o < 2; o++){

for (int p = 0; p < 2; p++){

cout << a[i][j][k][l][m][n][o][p];

}
cout << endl;

}
cout << endl;

}
cout << endl;

}
cout << endl;

}
cout << endl;

}
cout << endl;

}
cout << endl;

}
cout << endl;

}
Last edited on
One loop is enough:

1
2
3
4
5
6
7
8
#include <iostream>
#include <bitset>

int main()
{
    for(int n = 0; n < 256; ++n)
        std::cout << std::bitset<8>(n) << '\n';
}
Last edited on
Even without using std::bitset you shouldn't need more than two loops.
Topic archived. No new replies allowed.