Program: Using nested loops to calculate factorials


This program uses nested while loops to calculate various factorials. The workings for each factorial are displayed on the screen, along with the answer in bold:

Select and copy the C++ source-code at the bottom of this post.

Paste into a text editor, such as Nano or Geany.


Then save the new file, ending in .cpp

I used factorial.cpp

To compile from the command-line:

    g++ -o factorial.cpp factorial

To run from the command-line:


    ./factorial






Here's the code:



#include <iostream> // Program will be displaying some text on the screen

using namespace std; // Will be using standard identifiers cout and endl



int main()
{
    const string BOLD = "\e[1m";
    const string NORMAL = "\e[0m";
    cout << "FACTORIAL PROGRAM" << endl;
    cout << "=================" << endl;


    int factorialToCalculate = 1;

    // Outer while loop - controls WHICH factorial is being calculated
    while ( factorialToCalculate <= 10 )
    {
        cout << "Factorial of " << BOLD << factorialToCalculate << NORMAL << " is ";
        cout << factorialToCalculate; // Working starts with the number itself
        int num = factorialToCalculate;
        unsigned long long resultSoFar = num; // Builds up the product of all values


        // Inner while loop - calculates an individual factorial
        while ( num > 1 )
        {
            num--;
            cout << " x " << num;
            resultSoFar *= num;
        } // end of inner while loop


        // Display the final result for this factorial
        cout << " = ";
        cout << BOLD << resultSoFar << NORMAL << endl;
        factorialToCalculate++;


    } // End of outer while loop


    return 0;
}



Find out more - buy the book on Amazon!