Program: Generating tables of hexadecimal values


Similar to the previous example which uses recursion to generate all binary patterns that contain a certain number of digits. Tweaked to Generate hexadecimal values instead.
Compile and run on Raspberry Pie, Aplle Mac or Linux PC. ALTERNATIVELY you can paste the code into repl.it

Code below:


// Hexadecimal tables - Phil Gardner

#include <iostream>  // For screen and keyboard

using namespace std;  // Using cout, cin, endl

// - - - - - - - - - -

string pickFrom = "0123456789ABCDEF";  // The different characters that will be used to make the sequences

int numDigits;  // How many digits of hexadecimal to use

unsigned long long combinations;  // Counts up how many different sequences have been made so far

// - - - - - - - - - -

void appendToStub( string stub )
{
    // Decide whether the sequence of bits is long enough
    // If not yet long enough will trigger another recursive call
    bool callAgain = ( stub.length()+1 < numDigits );

    string newSequence;

    // First select a 0, then select a 1
    for ( int i = 0;   i < 16;   i++ )
    {
        newSequence = stub + pickFrom.at( i );

        // Display completed sequence of digits
        if ( newSequence.length() == numDigits )
        {
            cout << '\t' << newSequence << endl;
            combinations++;

        } // end of if that decides whether to display

        // Decide whether to recursively call again to add new digit to end of this sequence
        if ( callAgain )
            appendToStub( newSequence );

    } // end of for loop

} // end of function

// - - - - - - - - - -

int main()
{
    do
    {
        cout << endl << "How many digits? ";
        cin >> numDigits;

        if ( numDigits > 0 )
        {
            cout << endl;

            combinations = 0;
            appendToStub( "" );

            cout << endl << combinations << " combinations for " << numDigits << " digits." << endl;
        } // end of if numDigits > 0

    } while ( true == true );

} // end of main function