Friday, May 21, 2010

How do i make a C++ for() statement that will calculate the factorial of a number?

I'm taking a C++ computer programming course in college, and for a homework excercise it asks us to make a program, part of which needs to calculate the factorial of a number using a for() statement. I've almost got it, but i'm having some trouble.





So far, I know that if I have a number 'n' (which is an integer) and I want to calculate the factorial of n, i'm basically doing "n! = (n)(n-1)(n-2) ......" for when (n-x) %26gt; 0. So, I have the test for the for statement ((n-x)%26gt;0) (i think), but I'm stuck on the initialization and increment/decrement portion.





Basically, I'm using the factorial in a program whose goal is to calculate e^x (to the precision of .00001). I need to use a do while statement and the for statement. The do while continues to add terms, while the for calculates the factorial. I know there may be an easier way to do this, but this specific for the homework.





Thanks a bunch~

How do i make a C++ for() statement that will calculate the factorial of a number?
inline long fac (long x) {for(long i=x-1;i%26gt;1;i--) x*=i; return x;}
Reply:I would use a pseudocode or flowchart to get the clarity of thought





So if you write a general for loop for factorial


then probably it will go as follows [below isnt a pseudocode but more a c/c++ routine]








for (i=%26lt;initial value%26gt;-1, Temp=%26lt;initial value%26gt;;i%26gt;0;i--)


temp=temp*i;





To test your solution use dry run with each variable and what its value going to be through the iterations


Then you can make the code to be part of the function which can be sent called using the integer value and act as a building block in your c++ program
Reply:int calcFactorial(int n){





if(n %26lt;= 0)


{


return n;


}





int result = 1;





for(int i = 1; i %26lt;= n; i ++)


{


result *= i;


}





return result;


}


there you go. easy
Reply:C or C++:





int main() {





unsigned int Counter; /* In C++, you can make this declaration inside the for loop */





unsigned long Factorial = 1;





for (Counter = 5; Counter %26gt; 0; Counter--)





Factorial *= Counter;





printf("%i", Factorial);





return 0;





}


No comments:

Post a Comment