Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

binGen.cpp (in C++) This program will ask the user the number of bits needed (le

ID: 3834066 • Letter: B

Question

binGen.cpp (in C++)

This program will ask the user the number of bits needed (let us say that value goes into the variable “N”). The program will then generate ALL POSSIBLE “N”-bit BINARIES. For example, if the user enters 3 at the input prompt, the program would then generate:

Those are all 8 possibilities using 3 bits. Note that (and this will be a challenge) when the numbers are printed out, they are ALWAYS in forms of “N” bits (in this case N = 3), that is, you will need to PAD your printed numbers with enough “0”s on the left to always maintain “N” bits.

See example print out:

You will need to include string and cmath (in addition to iostream, of course) libraries. Some clues that will come in handy:

Here, we’re going to be using strings, not C-strings. The difference is subtle between the two types, but they are essentially both strings of characters (I’ll explain the differences more in lecture). As such, if you want to find out the length of a string (called, say, MyStr), you would NOT use strlen(MyStr), but rather MyStr.size().

To examine a character in a string, say MyStr, you can use indexing of the string, for example, if MyStr=”Hello”, then MyStr[0]=’h’, MyStr[1]=’e’, and so on. Indexing in C/C++ always starts at zero.

To convert a decimal number into binary, you can use the “Division/Remainder” algorithm, which I will cover in lecture on Thursday, 5/4, but you can see from the example below:

Explanation / Answer

PROGRAM CODE:

#include <iostream>
#include <cmath>
#include <string>
using namespace std;

int main() {
   int N, counter = 0;
   cout<<"How many bits to generate? ";
   cin>>N;
   int number_of_elements = pow(2,N);
   string binaryNumbers[number_of_elements];
   for(int i=0; i<number_of_elements; i++)
   {
       string value = "";
       int num = i;
       while(num/2 > 0)
       {
           value = to_string(num%2) + value;
           num = num/2;
       }
       //cout<<to_string(num%2)<<endl;
       value = to_string(num%2) + value;
       while(value.length() <N)
           value = "0" + value;
       binaryNumbers[counter++] = value;
   }
   for(int i=0; i<number_of_elements; i++)
       cout<<endl<<"The decimal number "<<i<<" is "<<binaryNumbers[i];
   return 0;
}

OUTPUT: