# Thread: HOw to find factorial of a given number in C++ Language?

1. ## HOw to find factorial of a given number in C++ Language?

Hi,

I am working on a program that asks a user to enter a # between 1 to 50 and finds the factorial of that. It uses recursive function to find it.

Here is what I got so far:

Code:
```    include <iostream>

using namespace std;

//function prototypes

int getNum();
int fact(int);
void printResult(int, int);

int main()
{
int num;
int ans;

num = getNum();
ans = fact(num);
printResult(num, ans);

cout << endl << endl;
}
int getNum()
{
int num;
cout << "\nEnter a number:";
cin >> num;
return num;
}
int fact(int num)
{

if (num == 0)
return 1;
else
return num * fact(num - 1);

}
void printResult(int num, int ans)
{
cout <<"\nfactorial of" << num << "is : " << ans;

}```

Thanks

edit: sorry, I have posted this again, because previously I accidentally posted on C section.

2. Your code looks correct (except for the part where you are calling "printResults", but your function declaration is "printResult"). What isn't working for you?

3. it gives me an error

4. Ah cant believe I did that mistake. Ok now I fixed the code but when I enter 20, it says factorial is -2102132736
but when I enter lower number like 5, it gives me correct answer 120. Whats wrong with 20?

5. Originally Posted by redworker
Ah cant believe I did that mistake. Ok now I fixed the code but when I enter 20, it says factorial is -2102132736
but when I enter lower number like 5, it gives me correct answer 120. Whats wrong with 20?
In 32-bit systems signed int can hold values from -2147483648 to 2147483647. Factorial of 20 is 2432902008176640000.

6. The answer hasn't changed from before. 20! is not representable in the int data type, since it is a 19-digit number. You need to pick a data type that can handle numbers of that size.