Recursive vs. Iterative

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.

The Recursive Approach

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

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
Share Button
Posted in Computer Science, Computing Concepts, Python - Advanced, Python Challenges

Our Latest Book

Follow this blog