-
WHen to use recursion ?
Hi,
According to my book it says that interation (loops), in many cases, can be use instead of recursion. But in some cases, recursion mimics the problem better. My question is simply when is a good time to use recursion and if possible provide an example.
note: I am more comfortable when using loops....
many thnx
-
loops are basically better: they use less stack space, they avoid function overhead etc.
Recursion can be more readable (except to newbies: to them it is confusing as hell). It has no speed or memory advantage that I know of.
-
Thnx, But can someone maybe post an example of when to use recursion?
thnx
-
it might be usefull when iterating trough tree's although such could be done iteratively as well
-
Everyone is saying they 'cannot think of a case where recursion is better', especailly in everyday production code.
The piece of code from your book that used recursion - remember?
It was the best way to show how the stack works - in other words it was the only good way to show how stacks store functions. It used recursion. But no sane programmer would use it to reverse a string. That was a good use of recursion.
Just as CB mentioned, it drove you nuts trying to figure it out.
-
Factorials are a good one:
Code:
long factorial(long num) {
if(num <= 1) return 1;
return num * factorial(num - 1);
}