TechArena Community How to calculate factorial of a number in C++

#1
26-08-2009
 Member Join Date: Jun 2009 Posts: 3,859
How to calculate factorial of a number in C++

I am having problem coding in C++. I want to calculate the factorial of a number that the user inputs but the problem is that whatever logic I try to do, it fails. So I am here to know what are the possibilities and how do you calculate factorial of a user specified number in C++?
#2
26-08-2009
 Member Join Date: Oct 2005 Posts: 2,389
Re: How to calculate factorial of a number in C++

You can calculate the factorial of a number in C++ using an external function as below and calling that function in your main code:

Code:
```int calfactorial (int x)
{
int finalx = 1;
if (x==1) return 1;
for (int i = 1; i <= x; ++i) finalx = finalx * i;
return finalx;
}```
#3
26-08-2009
 Member Join Date: May 2008 Posts: 685
Re: How to calculate factorial of a number in C++

Here is how factorial is calculated in C++:

Code:
```# include <iostream.h>
int factorial (int);
int main()
{
int result;
cout << "Enter your number: ";
cin >> result;
cout << "Factorial of " << result << "is "<< factorial (result) << endl;
}

int factorial (int n)
{
int fact = 1;
if  (n <= 1)
return 1;
else
fact  = n * factorial (n - 1);
return fact;
}```

 Tags: factorial