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

binGen.cpp This program will ask the user the number of bits needed (let us say

ID: 3606708 • Letter: B

Question

binGen.cpp 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: 001 010 011 100 101 110 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 "O's on the left to always maintain "N” bits.

Explanation / Answer


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

int zeroAt(string str) //Function tells the location of first occurance of zero in the string str, extream right is location one.
{
    int i;
    for( i=1 ; i<=str.size() ; i++) if ( str[str.size()-i] == '0' ) return i;
    return 0;
}

int decimal(string str) //Convert string to equivalent integer
{
    int i, n=0;
    for( i=1 ; i<=str.size() ; i++) n = n*2+(str[i-1]=='0'? 0:1);
    return n;
}


int main()
{  
    int N, sLen=0, i;
    string binRep ;

    cout << "How many bits to generate? ";
    cin >> N;

    for( i=0; i<N ; i++) binRep = binRep + '0'; // Make all the bits zero

    while( zeroAt(binRep) ) //Generate numbers till you have all ones in binary representation
      {
        cout << "The decimal number " << decimal(binRep) << " is "<< binRep << " ";

        //Increment in the binRep string
        int i, j; j=zeroAt(binRep);
        for( i=1; i<j ; i++) binRep[binRep.size()-i]='0'; // by setting all ones to zero
        binRep[binRep.size()-j]='1'; // and make first occurance of zero to one
      }
     cout << "The decimal number " << decimal(binRep) << " is "<< binRep << " "; // to print the last number
   
    return 0;
}