Greetings everyone! I hope to learn and become better in programming. But honestly, my heart fails me everytime I face a new assignment. This one is just another heartache.
Thing is, the question wants me to print out n-bit strings in lexicographical order ( meaning increasing order ). And I must use recursion. I am new to this concept let alone c++. I hope you can guide me here.
So the output of this program of mine is like so:
n = 1;
00
01
n=2;
00
01
00
01
00
000
001
000
001...
But, It needs to be like this :
n=1
0
1
n=2
00
01
10
11...
Can anyone tell me what i did wrong? and please tell me how to correct this. I know its simple, and I do apologize if this question has been asked before, but please teach me.
Thanks.
Dhanika.
My code:
#include<iostream>
#include<string>
using namespace std;
void printAllBitStrings(int n, string binary){
if (n == 1) {
cout << "0" << endl;
cout << "1" << endl;}
else {
printAllBitStrings(n - 1, binary );
binary[n] = '0';
printAllBitStrings(n - 1, binary );
binary[n] = '1';
}
}
int main(){
string binary;
int n;
cin >> n;
for(int i = 0; i < n; i++){
binary += "0";
printAllBitStrings( n, binary);
cout << endl;
}
return 0;
}