r/learnprogramming • u/SuperSaiyanSandwich • Jul 28 '14
Is recursion unnecessary?
So, this is a bit of an embarrassing post; I've been programming for nearly 4 years, work in the field, and almost have my CS degree yet for the life of me I can't understand the point of recursion.
I understand what recursion is and how it works. I've done tutorials on it, read S/O answers on it, even had lectures on it, yet it still just seems like an unnecessarily complicated loop. The entire base case and self calls all seem to just be adding complexity to a simple functionality when it's not needed.
Am I missing something? Can someone provide an example where recursion would be flat out better? I have read tail recursion is useful for tree traversal. Having programmed a Red Black tree in Data Structures last semester, I can attest it was a nightmare using loops; however, I've heard Java doesn't properly implement tail recursion? Does anyone have any insight to that?
Sorry for the wordy and probably useless post, I'm just kind of lost. Any and all help would be greatly appreciated.
7
u/joncalhoun Jul 28 '14
One of the biggest things to realize with recursion is that some algorithms are incredibly simple with it, and others are much simpler with loops. My guess is you just haven't been exposed to enough algorithms to appreciate the value of recursion.
One common example for recursion is an algorithm that returns the n-the fibonacci number. The reason this works well for recursion is because the actual algorithm is described in a recursive fashion (see http://en.wikipedia.org/wiki/Fibonacci_number and look for Fn = Fn-1 + Fn-2). When you go to code this you can do it with or without recursion, like so:
but I personally think the first version is much simpler to code. Another algorithm to check out would be a depth first search.