User Tools

Site Tools


cs509:printfactorial_program_developed_in_class

This is the printfactorial program that was developed in class on Wed, 2/20/13.

/*
Name: J. Chung

Write and test the void function printfactorial( int n ) that prints the factorial of an input integer. For example:

If printfactorial( 3 ), output is:

   3! = 3 * 2 * 1 = 6

If printfactorial( 4 ), output is:

   4! = 4 * 3 * 2 * 1 = 24
*/

#include <iostream>

using namespace std;

void printfactorial( int n )
{
    // output "n! = n * "
    cout << n << "! = " << n << " * ";

    unsigned long factorial = n;

    // Loop:
    while( 1 )
    {
        // Shrink n by 1
        n = n - 1;
        
        // output "n * "
        if ( n > 1)
            cout << n << " * ";
        else
            cout << n; // Don't print "*" if n = 1
            
        // Grow factorial
        factorial = factorial * n;
        
        // If n = 1, stop looping
        if ( n == 1 )
            break;
    }

    // output " = factorial"
    cout << " = " << factorial;
}




int main()
{
    // Test printfactorial:
    printfactorial( 5 );

    return 0;
}
cs509/printfactorial_program_developed_in_class.txt · Last modified: 2013/02/21 14:21 by jchung

Donate Powered by PHP Valid HTML5 Valid CSS Driven by DokuWiki