Click to See Complete Forum and Search --> : WHen to use recursion ?
iflash
Jan 6th, 2002, 10:00 AM
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
CornedBee
Jan 6th, 2002, 11:51 AM
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.
iflash
Jan 6th, 2002, 09:12 PM
Thnx, But can someone maybe post an example of when to use recursion?
thnx
kedaman
Jan 6th, 2002, 11:27 PM
it might be usefull when iterating trough tree's although such could be done iteratively as well
jim mcnamara
Jan 7th, 2002, 08:46 AM
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.
parksie
Jan 7th, 2002, 11:34 AM
Factorials are a good one:long factorial(long num) {
if(num <= 1) return 1;
return num * factorial(num - 1);
}
vbforums.com
Copyright Internet.com Inc., All Rights Reserved.