FACTORIAL


The C++ program featured in this tutorial web page computes N factorial (N!) using recursion and using iteration. If N is a natural number, then N! is the product of exactly one instance of each unique natural number which is less than or equal to N. If N is zero, then N! is one.

To view hidden text inside each of the preformatted text boxes below, scroll horizontally.

0! := 1. // base case: when N is zero
N! := N * (N - 1)! // recursive case: when N is any natural number

SOFTWARE_APPLICATION_COMPONENTS


C++_source_file: https://raw.githubusercontent.com/karlinarayberinger/KARLINA_OBJECT_summer_2023_starter_pack/main/factorial.cpp

plain-text_file: https://raw.githubusercontent.com/karlinarayberinger/KARLINA_OBJECT_summer_2023_starter_pack/main/factorial_output.txt


PROGRAM_COMPILATION_AND_EXECUTION


STEP_0: Copy and paste the C++ source code into a new text editor document and save that document as the following file name:

factorial.cpp

STEP_1: Open a Unix command line terminal application and set the current directory to wherever the C++ program file is located on the local machine (e.g. Desktop).

cd Desktop

STEP_2: Compile the C++ file into machine-executable instructions (i.e. object file) and then into an executable piece of software named app using the following command:

g++ factorial.cpp -o app

STEP_3: If the program compilation command does not work, then use the following commands (in top-down order) to install the C/C++ compiler (which is part of the GNU Compiler Collection (GCC)):

sudo apt install build-essential
sudo apt-get install g++

STEP_4: After running the g++ command, run the executable file using the following command:

./app

STEP_5: Once the application is running, the following prompt will appear:

Enter a nonnegative integer which is no larger than 12:

STEP_6: Enter a value for N using the keyboard.

STEP_7: Observe program results on the command line terminal and in the output file.


PROGRAM_SOURCE_CODE


Note that the text inside of each of the the preformatted text boxes below appears on this web page (while rendered correctly by the web browser) to be identical to the content of that preformatted text box text’s respective plain-text file or source code output file (whose Uniform Resource Locator is displayed as the green hyperlink immediately above that preformatted text box (if that hyperlink points to a source code file) or whose Uniform Resource Locator is displayed as the orange hyperlink immediately above that preformatted text box (if that hyperlink points to a plain-text file)).

A computer interprets a C++ source code as a series of programmatic instructions (i.e. software) which govern how the hardware of that computer behaves).

(Note that angle brackets which resemble HTML tags (i.e. an “is less than” symbol (i.e. ‘<‘) followed by an “is greater than” symbol (i.e. ‘>’)) displayed on this web page have been replaced (at the source code level of this web page) with the Unicode symbols U+003C (which is rendered by the web browser as ‘<‘) and U+003E (which is rendered by the web browser as ‘>’). That is because the WordPress web page editor or web browser interprets a plain-text version of an “is less than” symbol followed by an “is greater than” symbol as being an opening HTML tag (which means that the WordPress web page editor or web browser deletes or fails to display those (plain-text) inequality symbols and the content between those (plain-text) inequality symbols)).

C++_source_file: https://raw.githubusercontent.com/karlinarayberinger/KARLINA_OBJECT_summer_2023_starter_pack/main/factorial.cpp


/**
 * file: factorial.cpp
 * type: C++ (source file)
 * date: 14_JUNE_2023
 * author: karbytes
 * license: PUBLIC_DOMAIN
 */

/* preprocessing directives */
#include <iostream> // library for defining objects which handle command line input and command line output
#include <fstream> // library for defining objects which handle file input and file output
#define MAXIMUM_N 12 // constant which represents maximum N value

/* function prototypes */
int compute_factorial_of_N_using_recursion(int N, std::ostream & output);
int compute_factorial_of_N_using_iteration(int N, std::ostream & output);

/**
 * Compute N factorial (N!) using a recursive algorithm.
 * 
 * Assume that N is an integer value and that output is an output stream object.
 * 
 * For each compute_factorial_of_N_using_recursion function call, 
 * print an algebraic expression which represents N factorial.
 * 
 * 0! := 1. // base case: when N is smaller than 1 or when N is larger than MAXIMUM_N.
 * N! := N * (N - 1)! // recursive case: when N is larger than or equal to 1 and when N is smaller than or equal to MAXIMUM_N.
 */
int compute_factorial_of_N_using_recursion(int N, std::ostream & output)
{
    // base case: if N is smaler than 1 or if N is larger than MAXIMUM_N, return 1.
    if ((N < 1) || (N > MAXIMUM_N))
    {
        output << "\n\nfactorial(" << N << ") = 1. // base case";
        return 1;
    }
    // recursive case: if N is larger than or equal to 1 and if N is smaller than or equal to MAXIMUM_N, return N multiplied by (N - 1) factorial.
    else
    {
        output << "\n\nfactorial(" << N << ") = " << N << " * factorial(" << N - 1 << "). // recursive case" ;
        return N * compute_factorial_of_N_using_recursion(N - 1, output);
    }
}

/**
 * Compute N factorial using an iterative algorithm.
 * 
 * Assume that N is an integer value and that output is an output stream object.
 * 
 * For each while loop iteration, i,  print the ith multiplicative term of N factorial.
 * 
 * ---------------------------------------------------------------------------------------------------------------------------------------------------------------
 * If N is a larger than or equal to 1 and if N is smaller than or equal to MAXIMUM_N, 
 * N! is the product of exactly one instance of each unique natural number which is smaller than or equal to N. 
 * 
 * N! := N * (N - 1) * (N - 2) * (N - 3) * ... * 3 * 2 * 1. // if N is an arbitrarily large natural number (which, in this line, is equal to or larger than 7)
 * ---------------------------------------------------------------------------------------------------------------------------------------------------------------
 * 
 * If N is zero, then N! is one.
 * 
 * 0! := 1.
 * ---------------------------------------------------------------------------------------------------------------------------------------------------------------
 */
int compute_factorial_of_N_using_iteration(int N, std::ostream & output)
{
    int i = 0, F = 0; 
    i = ((N > 0) && (N <= MAXIMUM_N)) ? N : 0; 
    F = (N > 0) ? N : 1; 
    output << "\n\nfactorial(" << i << ") = ";
    while (i > 0) // Execute the code block encapsulated by the while loop while the condition "i > 0" is true.
    {
        output << i << " * "; // Print the value of i followed by " * " to the output stream.
        if (i > 1) F *= i - 1; // If i is larger than 1, multiply F by (i - 1).
        i -= 1; // Decrement i by 1.
    }
    output << "1.";
    return F;
}

/* program entry point */
int main()
{
    // Declare three int type variables and set each of their initial values to 0.
    int N = 0, A = 0, B = 0;

    // Declare a file output stream object.
    std::ofstream file;

    /**
     * If factorial_output.txt does not already exist in the same directory as factorial.cpp, 
     * create a new file named factorial_output.txt.
     * 
     * Open the plain-text file named factorial_output.txt 
     * and set that file to be overwritten with program data.
     */
    file.open("factorial_output.txt");

    // Print an opening message to the command line terminal.
    std::cout << "\n\n--------------------------------";
    std::cout << "\nStart Of Program";
    std::cout << "\n--------------------------------";

    // Print an opening message to the file output stream.
    file << "--------------------------------";
    file << "\nStart Of Program";
    file << "\n--------------------------------";

    // Print "Enter a nonnegative integer which is no larger than {MAXIMUM_N}: " to the command line terminal.
    std::cout << "\n\nEnter a nonnegative integer which is no larger than " << MAXIMUM_N << ": ";

    // Scan the command line terminal for the most recent keyboard input value.
    std::cin >> N;

    // Print "The value which was entered for N is {N}." to the command line terminal.
    std::cout << "\nThe value which was entered for N is " << N << ".";

    // Print "The value which was entered for N is {N}." to the file output stream.
    file << "\n\nThe value which was entered for N is " << N << ".";

    // If N is smaller than 0 or if N is larger than MAXIMUM_N, set N to 0.
    N = ((N < 0) || (N > MAXIMUM_N)) ? 0 : N; // A tertiary operation (using the tertiary operator (?)) is an alternative to using if-else statements.

    // Print "N := {N}." to the command line terminal.
    std::cout << "\n\nN := " << N << ".";

    // Print "N := {N}." to the file output stream.
    file << "\n\nN := " << N << ".";

    // Print a horizontal line to the command line terminal.
    std::cout << "\n\n--------------------------------";

    // Print a horizontal line to the command line terminal.
    file << "\n\n--------------------------------";

    // Print "Computing factorial N using recursion:" to the command line terminal.
    std::cout << "\n\nComputing factorial N using recursion:";

    // Print "Computing factorial N using recursion:" to the file output stream.
    file << "\n\nComputing factorial N using recursion:";

    // Compute N factorial using recursion, store the result in A, and print each function call in the recursive function call chain to the command line terminal.
    A = compute_factorial_of_N_using_recursion(N, std::cout);

    // Compute N factorial using recursion and print each function call in the recursive function call chain to the file output stream.
    compute_factorial_of_N_using_recursion(N, file);

    // Print the value of A to the command line terminal.
    std::cout << "\n\nA = factorial(" << N << ") = " << A << ". // " << N << "! = " << A << ".";

    // Print the value of A to the file output stream.
    file << "\n\nA = factorial(" << N << ") = " << A << ". // " << N << "! = " << A << ".";

    // Print a horizontal line to the command line terminal.
    std::cout << "\n\n--------------------------------";

    // Print a horizontal line to the command line terminal.
    file << "\n\n--------------------------------";

    // Print "Computing factorial N using iteration:" to the command line terminal.
    std::cout << "\n\nComputing factorial N using iteration:";

    // Print "Computing factorial N using iteration:" to the file output stream.
    file << "\n\nComputing factorial N using iteration:";

    // Compute N factorial using iteration and print each multiplicative term of N! to the command line terminal.
    B = compute_factorial_of_N_using_iteration(N, std::cout);

    // Compute N factorial using iteration and print each multiplicative term of N! to the file output stream.
    compute_factorial_of_N_using_iteration(N, file);

    // Print the value of B to the command line terminal.
    std::cout << "\n\nB = factorial(" << N << ") = " << B << ". // " << N << "! = " << B << ".";

    // Print the value of B to the file output stream.
    file << "\n\nB = factorial(" << N << ") = " << B << ". // " << N << "! = " << B << ".";

    // Print a closing message to the command line terminal.
    std::cout << "\n\n--------------------------------";
    std::cout << "\nEnd Of Program";
    std::cout << "\n--------------------------------\n\n";

    // Print a closing message to the file output stream.
    file << "\n\n--------------------------------";
    file << "\nEnd Of Program";
    file << "\n--------------------------------";

    // Close the file output stream.
    file.close();

    // Exit the program.
    return 0;
}

SAMPLE_PROGRAM_OUTPUT


The text in the preformatted text box below was generated by one use case of the C++ program featured in this computer programming tutorial web page.

plain-text_file: https://raw.githubusercontent.com/karlinarayberinger/KARLINA_OBJECT_summer_2023_starter_pack/main/factorial_output.txt


--------------------------------
Start Of Program
--------------------------------

The value which was entered for N is 12.

N := 12.

--------------------------------

Computing factorial N using recursion:

factorial(12) = 12 * factorial(11). // recursive case

factorial(11) = 11 * factorial(10). // recursive case

factorial(10) = 10 * factorial(9). // recursive case

factorial(9) = 9 * factorial(8). // recursive case

factorial(8) = 8 * factorial(7). // recursive case

factorial(7) = 7 * factorial(6). // recursive case

factorial(6) = 6 * factorial(5). // recursive case

factorial(5) = 5 * factorial(4). // recursive case

factorial(4) = 4 * factorial(3). // recursive case

factorial(3) = 3 * factorial(2). // recursive case

factorial(2) = 2 * factorial(1). // recursive case

factorial(1) = 1 * factorial(0). // recursive case

factorial(0) = 1. // base case

A = factorial(12) = 479001600. // 12! = 479001600.

--------------------------------

Computing factorial N using iteration:

factorial(12) = 12 * 11 * 10 * 9 * 8 * 7 * 6 * 5 * 4 * 3 * 2 * 1 * 1.

B = factorial(12) = 479001600. // 12! = 479001600.

--------------------------------
End Of Program
--------------------------------

This web page was last updated on 06_NOVEMBER_2024. The content displayed on this web page is licensed as PUBLIC_DOMAIN intellectual property.