sandrockj

Posted on

# Recursion or Loop?

When should you use a recursive function instead of a loop statement? Likewise, when should you use a loop statement instead of recursion?

Oftentimes I find myself a bit unsure of how to answer this question, and I find myself reminiscing of a toy problem from the past. The problem was this:

Write a set of code that will evaluate whether or not the provided String variable is a palindrome. Your code should determine a boolean value reflecting this condition.

It took me a while to solve the code, given some of the constraints and edge conditions. However, eventually I was able to solve this problem through the use of a recursive function.

After a while I wondered, would this be possible with a For Loop? And so, I set out to find an answer and began experimenting. What I found is that, sure enough, this can be done with a Loop statement as well.

As I reflected upon the two sets of code, I found myself somewhat frustrated because it felt like I still had not grasped why you would prefer a recursive statement over a Loop. I came across a discussion on StackExchange that shed some light on the topic. A developer by the name of Scant Roger stated the following:

"Ultimately, there's nothing recursion can compute that looping can't, but looping takes a lot more plumbing. Therefore, the one thing recursion can do that loops can't is make some tasks super easy...Often the recursive solution to a problem is prettier."

It became apparent to me that Roger was absolutely right; I found that it was much easier for me to write the recursive solution than it was to develop the same solution with a Loop statement. If it is easier to create a recursive solution, and to later redesign it as a Loop (to reduce code complexity) I think that is fine.

What are your thoughts? I am still new to coding, and I would love to hear from everyone else!