View Full Version : c++ n factorial program
GSXdan
03-26-2003, 05:04 PM
How would someone go about writing a program to compute the n factorial of a number? (n factorial is written as n!)
n! = n * (n-1) * (n-2) * .. * 1 for values of n greater than or equal to 1
0! = 1
for example, 5! = 5*4*3*2*1 = 120
thanks ^dan
doctorgonzo
03-26-2003, 05:30 PM
I'll give it a shot:
int main(int argc, char *argv[])
{
int numb;
int fact;
cout<<"Enter a number:"<<endl;
cin>>numb;
if(!numb) { //Check to see if numb is 0
cout<<"0! is 1";
return 0;
}
fact=1;
while(numb) //Do while numb is not 0
{
fact*=numb;
numb--;
}
cout<<fact;
return 0;
}
GSXdan
03-26-2003, 06:36 PM
As always doctorgonzo, thank you very much for a very timely response, and of course, it works:)
thanks again ^dan
vBulletin® v3.7.0, Copyright ©2000-2008, Jelsoft Enterprises Ltd.