/*****************************************************************************
 * This program provides a simple example of a recursive function definition. 
 * The factorial of a non-negative integer 'n' is the product of '1' with all 
 * the integers between '1' and 'n' inclusive. Among many other applications, 
 * The function is useful in expressing Taylor series in calculus.
 ******************************************************************************/

#include<iostream>
#include<stdexcept>

using std::cout; using std::cin; using std::endl;
using std::domain_error;

long factorial(int n)
{
	if(n<0) //The function is not defined for negative integers.
		throw domain_error("factorial of a negative");
	if(n==0)// This is the base case. 
		return 1;
	else // Work toward the base case.
		return n*factorial(n-1);
}
	

int main()
{
	int n, n_fac;
	cout<<"Please enter a non-negative integer: ";
	cin>>n;
	try
	{
		n_fac=factorial(n);/* Apply 'factorial' before output, so
				      we can throw the exception before
				      any output.
				      */
		cout<<n<<" factorial = "<<n_fac<<".\n";
	}
	catch(domain_error e)
	{
		cout<<e.what();
		return 1;
	}

	

	
	
	return 0;
}

