Ask your own question, for FREE!
MIT 6.00 Intro Computer Science (OCW) 21 Online
OpenStudy (anonymous):

int factorial (int n); what does this command do?

OpenStudy (anonymous):

please help this is a c programing question.

OpenStudy (anonymous):

As you have it written there, it is a function declaration for the function named "factorial" of type "integer" with one parameter "n" of type "integer". If you're talking about the common recursive problem it usually looks something like this: if (n == 1) { return 1; } else { return n * factorial(n - 1); } It simply returns the value of 1 if your n = 1. Otherwise, it will take n and multiply it by the factorial(n-1). And can be solved as such: If n = 4, for example, then you start with factorial(4). Your first run through the function would return: 4 * factorial(3);. This new call to factorial(3) is calling the same function that you're already in (a property of recursion) and a new instance of that function is created on the side. In the new instance of the function, you parameter is 3 instead of 4, so you get: 3 * factorial(2) .. and the next recursive call creates a new instance of the function and gives you 2 * factorial(1). The final recursive call, factorial(1), which is still a new instance of the function, is a bit different as you've now hit a return statement that is no longer recursive. The return value at this point is 1 (since your n value equals 1). At this point, you work backward and fill in the values. Since you now know that factorial(1) is 1, 2 * factorial(1) is the same thing as 2 * 1, which is 2. Now that you have factorial(2) = 2, you can plug that into 3 * factorial(2) to get 3 * 2, or 6, for factorial(3), and finally, now that you have factorial(3), you can plug it into 4 * factorial(3), to find factorial(4), and get 4 * 6 which is 24 and your final solution to factorial(4). Do note that although this function is often used to teach recursion it can also be a useful lesson in when NOT to use recursion. Recursion is quite slow because each instance of the function must be stored in the stack and copies must be made in memory for scope isolation. The factorial function above can be written iteratively for much better performance (especially as n approaches infinity).

Can't find your answer? Make a FREE account and ask your own questions, OR help others and earn volunteer hours!

Join our real-time social learning platform and learn together with your friends!
Can't find your answer? Make a FREE account and ask your own questions, OR help others and earn volunteer hours!

Join our real-time social learning platform and learn together with your friends!