0

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;
}

Edited by Wong23: n/a

3
Contributors
2
Replies
3
Views
7 Years
Discussion Span
Last Post by dkalita
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

0

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

Edited by dkalita: n/a

This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.