Recursive vs. Iterative Algorithms

The purpose of this blog post is to highlight the differnce between two types of algorithms: Iterative and Recursive algorithms.

The challenge we will focus on is to define a function that returns the result of 1+2+3+4+….+n where n is a parameter.

The Iterative Approach

The following code uses a loop – in this case a counting loop, aka a “For Loop”.
This is the main characteristic of iterative code: it uses loops.

# iterative Function (Returns the result of: 1 +2+3+4+5+...+n)
def iterativeSum(n):
    total=0
    for i in range(1,n+1):  
        total += i
    return total

The Recursive Approach

The following code uses a function that calls itself. This is the main characteristic of a recursive approach.

# Recursive Function (Returns the result of: 1 +2+3+4+5+...+n)
def recursiveSum(n):
    if (n > 1):
        return n + recursiveSum(n - 1)
    else:
        return n

You can visualise/trace this recursive function on recursivevisualizer.com

Let’s see both approaches in action

Your Challenge:

Tweak both functions above to:

  • add up only even numbers: e.g. 2+4+6+8+….+n-2+n
  • add up only odd numbers: e.g. 1+3+5+…+n-2+n
  • add up numbers, counting in 5: e.g. 5+10+15+…+n-5+n

Did you like this challenge?

Click on a star to rate it!

Average rating 3 / 5. Vote count: 2

No votes so far! Be the first to rate this post.

As you found this challenge interesting...

Follow us on social media!