Overview of Iterative Functions
Here, we will learn about Iteration.
We'll cover the following
What is Iteration?
Iteration means repeating some steps to achieve the desired outcome. In computer programming, this may involve a mechanism such as a loops.
Iterative code is a block of code that runs in a loop. In other words, the same code is repeated over and over again. The idea is similar to that of recursion.
As we are learning recursion, it is important to have an overview of iteration as well. You might have written simple programs that involve iterating over an array, list, etc.
The concept of Recursion and Iteration is to execute a set of instructions repeatedly.
However, the difference between them is that recursion is simply a method call in which the method being called is the same as the one making the call. Iteration, on the other hand, is when a loop is repeatedly executed until a certain condition is satisfied.
Both recursion and iteration depend on a condition which determines whether to stop execution or continue it.
Format of an Iterative Function
Each iterative function consists of a loop and a conditional statement that determines whether to continue iteration or to stop.
In the illustration above the dotted line encapsulates the iterative part of the code flow.
Syntax of an Iterative Function
Let’s have a look at how an iterative function is coded in python:
def IterativeFunction() :
<some local variables if required>
while <someCondition == TRUE> :
# Perform a task
Calculating Factorial of a Number
Let’s have a look at the iterative code for calculating factorial of a number. We have already looked at the recursive code in a previous lesson.
def factorial(targetNumber) :index = targetNumber - 1 # set the index to target - 1while index >= 1 :targetNumber = targetNumber * index # multiply targetNumber with one less than itself, i.e, index hereindex -= 1 # reduce index in each iterationreturn targetNumber# Driver CodetargetNumber = 5result = factorial(targetNumber)print("The factorial of " + str(targetNumber) + " is: " + str(result))
In the Iterative version, we initiate a simple while
loop and multiply targetNumber
with index
in each iteration. index
is also reduced by in each iteration. This step is important because other wise our program will be stuck in an infinite loop. The value of index
initially is targetNumber - 1
.
Let’s dry run this code by keeping track of the variables.
In the next lesson, we highlight the major differences between iteration and recursion.