 Linus Rastegar -4 years ago 71
C++ Question

# Rewriting code with many nested loops

I'm wondering whether how you can write something like this recursively or using a different loop system:

``````std::string a = "00000000";
for (int i = 0; i<8; i++) {
a[i] = '1';
for (int j = 0; j<8; j++) {
if (i!=j) {
a[j] = '1';
... //more for loops with the same structure
std::cout<<a[j]<<"\n";
a[j] = '0';
}
a[i] = '0';
}
``````

I'm trying to print out every possible eight bit combination of 0s and 1s without using any libraries (except bitset if I have to). If I do it this way, I'll end up with 8 for loops, which is a bit much. I'm wondering whether there is a way to condense this using either recursion or a clever trick with using the standard do/while/for loops. Alex Bohm
Answer Source

This task can be achieved with a simple for loop and binary operations. Bitshift `i` by an amount, then `&` it by 1 to mask that bit.

``````#include <iostream>
void printBinary()
{
for(int i = 0; i < 256; i++){
for(int bit = 7; bit >= 0; bit--){
std::cout << (i >> bit & 1);
}
std::cout << std::endl;
}
}
``````
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download
Latest added