r/computerscience • u/UselessPlinth • May 03 '21
When to use recursion?
So I am getting a little bit ahead of myself here, I'm still in high school and I'm entering (hopefully) AP Java next year (or computer science A). One of the topic there is recursion, and I've done a little digging, and I find recursion really interesting, but what I was wondering was when do programmers use recursion? Like, can a for loop just do the job or does it help with computer memory and processing, when is the best time to use recursion?
141
Upvotes
163
u/usernameistakencry May 03 '21
Anything that can be done with recursion can be done with a loop.
Some problems are much much easier to solve with recursion , example: most tree algorithms and graph algorithms.
Recursion can easily solve a problem but can be really really bad in terms of memory use for example Fibonacci numbers. But there are things like caches you can use to improve these problems so it is a trade off sometimes.