factorial.cpp


//factorial.cpp

#include <iostream>
using namespace std;

//include a function prototype so the compiler knows that factorial has been declared

int factorial (int n);

//a test program for the factorial function
int main ()
{
	//input a value for the factorial computation
	cout << "Enter a positive integer n: ";
	//declare n as an integer before it is used in a program statement
	int n;
	//use standard console input object
	cin >> n;
	//make sure n is greater than zero
	if (n >=0)
		cout << "factorial(" << n << ") = " //display answer
				<< factorial (n) << endl;
	else
	{
		cerr << "factorial(" << n << ") undefined" << endl;
		return 1;
	}
	return 0;
}

//A function to compute the factorial of its argument -- argument must be positive integer

int factorial(int n)
{
	//declare local variable ans

	int ans =1;

	while (n > 1)
	{
		ans = ans * n;
		n = n-1;
	}
	return ans;
}


Results

C:\classes\ece538\work>factorial
Enter a positive integer n: 4
factorial(4) = 24


Maintained by John Loomis, updated Sun Dec 31 17:09:35 2006