Recursion vs Iteration

Donna Lee
3 min readMar 23, 2021

There’s more than one way to skin a cat. One of the great (and confusing) things about coding is that there is always more than one way to approach a problem. An example of this is recursion and iteration. Both of these are ways of repeatedly executing a set of instructions. Let’s dive a little deeper so you can decide which one is right for your use case.

What is iteration?

Iteration is when a loop repeatedly executes until the controlling condition becomes false Tutorials Point

Iteration is a set of instructions that is repeatedly executed. It uses repetition structure, which means the decision whether to repeat the code is based on the evaluation of a logical expression. An iteration terminates when the loop condition fails. Two common iterations are the for loop and the while loop.

What is recursion?

Recursion is when a statement in a function calls itself repeatedly — Tutorials Point

Recursion is a process that is always applied to a function. It uses selection structure, which performs different processes based on whether a boolean condition is true or false. A complicated function can be split down into smaller parts using recursion. Recursive functions also are generally shorter and more concise. The function terminates when a base case is recognized.

Solving Fibonacci Sequence: For Loops vs Recursion

The fibonacci sequence is one that is often used to showcase the recursion process. Let’s take a look at how we can solve the sequence using both methods. Then we will go into the pros and cons of recursion and iteration.

For Loops

N = int(input("Please enter number of elements in Fibonacci Series: "))#initialize the list with starting elements: 0, 1
fibonacciSeries = [0,1]
if N>2:
for i in range(2, N+1):
#next elment in series = sum of its previous two numbers
nextElement = fibonacciSeries[i-1] + fibonacciSeries[i-2]
#append the element to the series
fibonacciSeries.append(nextElement)
print(fibonacciSeries[N])

Recursion

def fib(n):
if n > 1:
return fib(n-1)+fib(n-2)
elif n <= 1:
return n

Just by looking at the code, you may notice a few key differences.

Attributes of Each

Is one better than the other?

As with most things in life, the answer is it depends. Recursion works great with tree traversal algorithms. However, it doesn’t work as well when the call stack grows linearly. An iterative approach would be better in this case. Other things to consider is also the code that is going to be built on top of your own. Recursion can be hard to QA and debug by nature.

Resources:

Tutorial Point on Differences between Recursion and Iteration

Python Examples

--

--