I am trying to write a program that generates all the binary codes given an input number (for the number of bits). For example, if the user inputs 3, it should generate all the numbers below:
000
001
010
011
100
101
110
111
The function is called generateBinaryCode(), and it has to be recursive (that's the challenge of the question).
The following is my attempt but it doesn't work. Can anyone please offer me some insights?
Thanks in advance.
#include <iostream>
#include <string>
#include <vector>
using namespace std;
vector<string> generateBinaryCode(int nBits);
int main()
{
int input;
while (true)
{
cout << "Enter an integer (any negative numbers are sentinel): ";
cin >> input;
if (input < 0) break;
for (unsigned i = 0; i < generateBinaryCode(input).size(); i++)
cout << generateBinaryCode(input).at(i) << endl;
}
return 0;
}
vector<string> generateBinaryCode(int nBits)
{
vector<string> result;
int size = result.size();
std::vector<string>::iterator it;
if (nBits == 1) {
result.push_back("0");
result.push_back("1");
} else {
result = generateBinaryCode(nBits - 1);
for (unsigned int i = 0; i < result.size(); i++)
{
result.push_back("0" + result.at(i));
result.at(i) = "1" + result.at(i);
}
}
return result;
}