Download Quick Currency Converter

Fact/Factorial of a number C/C++

Description: The project finds the fact/factorial of a given positive number provided that the number is not greater than 20. The project uses recursion to calculate factorial.

Difficulty: Easy

Language: C++

Compiler/IDE: Visual Studio, dev C++ (others will work as well)

View Source


unsigned long long int fact(unsigned long long int n);

int main()
	long long int n;
	do {
	std::cout<<"Write a number to calculate factorial; -1 to quit \n";
	std::cin>> n;
	if ( n == -1) 

	if ( n < 0 ) {
		std::cout<<"Write a positive number \n" ;
	else if (n >20)
          std::cout<<"Number too big \n" ;
	std::cout<<"The factorial of " << n << " is " << fact(n) << "\n";
	} while ( n!= -1) ;

unsigned long long int fact(unsigned long long int n) 
	if (n<=1 ) 
		return 1;
        	return n * fact(n-1) ;

Notes:The project calls a simple function that calculates factorial using recursion. (If you are not familiar with recursion, check out the tutorial links). If the number passed is 1, it simply returns 1, otherwise, the function splits the calculation and calls "fact" again.

Alternatively you can use our project Pascal Triangle that has a simple iterative function for factorial.