Iteration Strategy: The basic strategy in the programming world.

May 21, 2023 / 3 min read /

--- views

Last Updated May 21, 2023
Iteration Strategy: The basic strategy in the programming world.

An iteration strategy consists in using loops to repeat a process until a condition is met. Each step in a loop is called an iteration. We can use different types of loops, such as the "for" loop or the "while" loop, to control how many times we repeat the steps šŸ’«.

Let's say you have a list of numbers, and you want to find the largest number in that list. By using iteration, you can iterate through each element of the list and keep track of the maximum value encountered.

max.py

1
numbers = [8, 15, 3, 12, 10, 6]
2
3
max_number = numbers[0] # Assuming the first number is the maximum
4
5
for num in numbers:
6
if num > max_number:
7
max_number = num
8
9
print("The maximum number is:", max_number)

Here we are iterating over each element with for loop and comparing each number with the current max_number. If a number is found to be greater than the current maximum, we update max_number with that number.

After iterating through the entire list, we print out the final value of max_number, which represents the maximum number in the given list. In this case, the output would be: "The maximum number is: 15." It loops over all numbers in the inputs, performing a fixed number of operations for each number. Hence the this simple max number finding algorithm is O(n).

Nested Loops

A nested loop is a loop that is contained within another loop. For example, a for loop inside a while loop is a nested loop. Nested loops can be used to iterate over multiple collections of data. The power set of a set is the set of all possible subsets of that set. We use a nested loop for computing power sets. Given a collection of objects S, the power set of S is the set containing all subsets of S.

Imagine you have a set of instructions that you want to repeat multiple times. That's where nested loops come into play! It's like having loops inside loops, each with its own set of instructions. This allows you to execute certain code repeatedly and create fascinating patterns or perform complex computations.

Let's see an example to understand this better. Suppose we want to print a triangle pattern using asterisks on the screen. We can achieve this with the help of nested loops. Take a look at the following Python code:

triangle.py

1
for i in range(5): # Outer loop for the number of rows
2
for j in range(i + 1): # Inner loop for the number of asterisks in each row
3
print("*", end=" ")
4
print() # Moves to the next line after each row

Run this code, and you'll witness a fantastic triangle being formed on your screen. Each iteration of the outer loop controls the number of rows, while the inner loop takes care of printing the corresponding number of asterisks in each row. Pretty cool, right? āœØ