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)
for i in range(1,n+1):
total += i
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)
if (n > 1):
return n + recursiveSum(n - 1)
You can visualise/trace this recursive function on recursivevisualizer.com
Let’s see both approaches in action
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