Click here to Skip to main content
15,885,366 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi
I've implemented factorial recursively this way:

C++
int factorial(int x){
	if (x <= 0)
		return 1;
	else
		return (x*factorial(x - 1));
}

int _tmain(int argc, _TCHAR* argv[])
{
	std::cout << "Please enter your number :::";
	int x;
	std::cin >> x;
	std::cout<<"factorial(" << x << ") = "<< factorial(x);
	getchar(); getchar();
}


which way of implementing such code is more useful writing it using iteration and loops or writing it recursively such as above?
Posted

It is better to use Iterations/loops in this case.
For details explanation please visit:
http://www.informit.com/articles/article.aspx?p=1874865[^]

Thanks.
 
Share this answer
 
It depends on what you understand by "best". Is it fastest, easiest code to comprehend, most elegant, easiest to maintain, etc.?

If you had to implement it as a library function the speed would obviously play a big role. And that would certainly have you implement it in a loop. A recursive implementation is much slower, because each multiplication does also consume the time of a procedure call. So most people will say that the iterative implementation is the "best". If you were to give a programming class and wanted to demonstrate the concept of recursive functions your goal could be different, though.
 
Share this answer
 
Comments
CPallini 28-Jan-15 9:23am    
Of course. Have my 5.
nv3 28-Jan-15 10:33am    
Thank you!
You are correct, in this case recursion is best and cleanest.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900