|
-
Jan 6th, 2002, 11:00 AM
#1
Thread Starter
Hyperactive Member
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
-
Jan 6th, 2002, 12:51 PM
#2
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.
All the buzzt
 CornedBee
"Writing specifications is like writing a novel. Writing code is like writing poetry."
- Anonymous, published by Raymond Chen
Don't PM me with your problems, I scan most of the forums daily. If you do PM me, I will not answer your question.
-
Jan 6th, 2002, 10:12 PM
#3
Thread Starter
Hyperactive Member
Thnx, But can someone maybe post an example of when to use recursion?
thnx
-
Jan 7th, 2002, 12:27 AM
#4
transcendental analytic
it might be usefull when iterating trough tree's although such could be done iteratively as well
Use  
writing software in C++ is like driving rivets into steel beam with a toothpick.
writing haskell makes your life easier:
reverse (p (6*9)) where p x|x==0=""|True=chr (48+z): p y where (y,z)=divMod x 13
To throw away OOP for low level languages is myopia, to keep OOP is hyperopia. To throw away OOP for a high level language is insight.
-
Jan 7th, 2002, 09:46 AM
#5
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.
-
Jan 7th, 2002, 12:34 PM
#6
Monday Morning Lunatic
Factorials are a good one:
Code:
long factorial(long num) {
if(num <= 1) return 1;
return num * factorial(num - 1);
}
I refuse to tie my hands behind my back and hear somebody say "Bend Over, Boy, Because You Have It Coming To You".
-- Linus Torvalds
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|