can someone help me with this problem(factorial)
everything is working fine but when I enter a negative number the program crashes somewhere....but n can be any non-negative number
Here is da code

#include <iostream>
#include <string>

using namespace std;

int fact(int n){
if (n==0)
return 1;

else
return fact(n-1)*n;
}
int main()
{
int number;
char response;

do{

cout<<"Enter number: ";
cin>>number;
cout<<"factorial: "<<fact(number)<<endl;

cout<<"Do you want to continue: ";
cout<<"(Press Y/N)"<<endl;
cin>>response;

}while((response=='y') || (response=='Y'));
system("PAUSE");
return 0;
}

The formula for finding a factorialis:
n(n-1)(n-2)(n-3).........1,right?
If you have a negative number e.g -1, what would be the factorial?
-1(-2)(-3)(-4)(-5)(-6)..... it goes on to infinity.. That is why your program crashes.i.e if n is negative, there is no way n-1 can be equal to 1.

Please,if this helped, mark your thread as solved and add to my reputation points. Thanks!!

"Show me your code and I will tell you who you are.."--Tkud

ofcourse it wil crash because it is getting into an infinite loop because its not reaching the final condition.

make your condition from if(n==0) to if(n<1) in the factorial function

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.