0% found this document useful (0 votes)
49 views15 pages

Loops and Iterations

Uploaded by

lancer6yt
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
49 views15 pages

Loops and Iterations

Uploaded by

lancer6yt
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 15

Loops and Iterations

Topics
●​ For loops

●​ While loops

●​ Loop control Statements

○​ Break

○​ Continue

●​ Time complexity of loops

●​ Nested loops and optimization

●​ Competitive coding cases

Learning Objectives
●​ Understand how to use loops to repeat tasks.

●​ Differentiate between while and for loops.

●​ Understand control loop execution using break and continue statements.

●​ Analyse the time complexity of loops (O(n), O(log n), O(n2))

●​ Implement nested loops in multi-level iteration and optimize for performance.

●​ Handle edge cases in loop-based problems, including empty inputs and large

values.

●​ Solve competitive programming challenges using loops and iteration principles.


1.​Introduction to Loops
One way to tell a computer to keep doing something until you tell it to stop is using loops.
Loops in programming are used to repeat a block of code multiple times. They automate
repetitive tasks and make programs more efficient. For example, imagine you have five
dirty shirts that need to be washed. You could choose to wash each one separately, but
that would take ages. Instead, you could keep washing the shirts one by one until they are
all done. This is exactly what a loop does in programming—it repeats an action until a
certain condition is met.

2.​Types of Loops
2.1.​For Loop
A for loop repeats an action a set number of times. In more technical terms, this process is
called iteration. The word iterate in this context means repeating a set of instructions
multiple times until a specific condition is met or for a fixed number of times. For the rest
of this lesson we shall use the term iterate to refer to the earlier explained process.

Here’s an example of how we use for loops in python:

for i in range(5):
print(“Iteration:”, i)

#In python, we use the keyword for to start a for loop.

# i is called a loop variable. A loop variable is a variable that changes its value in each
iteration of a loop. In this case, i changes its value from 0 to 1 to 2 etc. until the iteration
stops.
#The keyword in assigns the loop variable( i ) to each value from the sequence. Imagine
you had 5 sweets to give to friends, think of in as a helper that takes one sweet at a time
and gives it to your friends until the sweets are gone.

# range is an inbuilt function in python used to generate a sequence of numbers. In our


code above, we used it to generate a sequence of five numbers from 0-4.
Our loop runs 5 times.
#NOTE: The range function starts counting from 0

#Just like the range function, print is also an inbuilt python function. It is used to display
output on the screen.

#The table below show the output of this for loop

Loop Iteration Value of i Output

1st 0 Iteration: 0

3rd 1 Iteration: 1

4th 2 Iteration: 2

5th 3 Iteration: 3

6th 4 Iteration: 4

★​ Common Mistakes
○​ Using range and expecting numbers from 1 to 5 (it starts at 0)
○​ If you want to list numbers from 1, use range(1,6). This displays numbers
from 1-5.

★​ Practice question
Write a for loop that prints numbers from 10 to 15.
2.2.​While Loop
Let’s say you want to bounce a ball until you get tired. You can say to yourself “I’ll keep on
bouncing this ball until I get tired.” So, you bounce the ball and stop when you get tired.
This is precisely what a while loop does. A while loop runs until a condition becomes false.

Let’s put that into practice in this example:


count = 0
While count < 5:
print(“Iteration: ”,count)
count += 1

#We start with an initial value of 0 stored in the variable count, the loop runs while count is
less than 5 meaning it keeps on running until count reaches 5.

#Each time the loop runs, Python displays the current count and then adds 1
to it, ensuring the loop progresses until it reaches 5.

#The table below displays the results of this loop.

Count Variable Condition Output

0 True Iteration: 0

1 True Iteration: 1

2 True Iteration: 2

3 True Iteration: 3

4 True Iteration: 4

5 Fasle(Loop stops)

★​ Common Mistakes
Forgetting count+=1, causing an infinite loop (loop never stops!)
Always ensure your loop modifies the condition variable inside the loop.

★​ Practice question
Write a while loop that prints numbers from 5 to 10.

3.​Loop Control Statements


Loop Control statements help us manage how loops behave. There’s two kinds of loop
control statements. The break statement which is used to prematurely exit a loop and the
continue loop which skips the current iteration and moves to the next.

3.1.​Break
The break statement acts like a stop button because it immediately exits the loop,
stopping it from continuing to its natural end.

for i in range(5):
if i == 3:
​ break
print(“Iteration:”, i)

#In this example, we are telling Python to stop running the code once the value of i is 3 .

#The table below shows what’s happening in our loop

Iteration (i) Condition(i == 3) Action Taken Output


0 False print Iteration: 0

1 False print Iteration: 1

2 False print Iteration: 2

3 True break (No output)

4 (Not reached - -
because loop was
broken)
# In the table above, we can see that there is no output after the loop is broken.

★​ Practice question
Modify the above code so the loop stops when i ==2

3.2.​Continue
In a situation where you are eating a bunch of bananas one at a time and you
come across a rotting banana, instead of stopping eating entirely, you can just
skip that banana and continue eating. The continue statement works the same
way. It tells Python to skip the current iteration but keep on going with the rest.

Here’s an example to demonstrate this better:

for number in range(1, 6):


if number == 3:
continue
print(number)

# When the number is equal to 3, the continue statement tells Python to skip 3 and
continue with the other numbers.
#Here’s a visual representation of what’s happening in the code above.

Iteration Value of number Condition Action


(number == 3)

1 1 False Prints 1

2 2 False Prints 2

3 3 True (Skips) Does not print ​​


anything

4 4 False Prints 4

5 5 False Prints 5

★​ Common Mistakes
Not placing continue before print()
continue should come first so that it skips printing

★​ Practice question
Modify the above code to skip number 2 instead of 3

4.​Mini Project: ATM Simulation


Let’s put what we’ve learned so far to the test!

Task: Simulate an ATM system with options for withdrawal and balance
checking.

Requirements
●​ Display a menu with options.
●​ Allow the user to check their balance and withdraw money
●​ Ensure proper loop control

Worked example

balance = 5000

while True:
​ ​ print("\nATM Menu:")
print("1. Check Balance")
print("2. Withdraw Money")
print("3. Exit")

​ ​ choice = int(input("Choose an option: "))

if choice == 1:
print(f"Your current balance is: ${balance}")

elif choice == 2:
amount = int(input("Enter withdrawal amount: "))
if amount <= balance:
balance -= amount
print(f"You withdrew ${amount}. New balance: ${balance}")
else:
print("Insufficient funds!")

elif choice == 3:
print("Thank you for using the ATM!")
break
else:
print("Invalid choice. Please select again.")

Bonus Tasks

Create your own system and


1.​ Loop until user inputs correct pin
a.​ Instead of giving up after one wrong PIN attempt, make the program loop until the
user enters the correct PIN!
2.​ Loop until user inputs valid withdrawal
a.​ Make sure users can’t withdraw more money than they have.​
If they try, loop back and ask again!
3.​ Loop to display menu until user chooses to exit
a.​ Instead of stopping after one transaction, keep the ATM running until the user
chooses to exit.

5.​Time Complexity of loops


Time complexity of loops measures how long a loop takes to run as the input size
increases. It helps programmers understand whether their code will run fast or slow.
Imagine you have a basket of 10 apples. If you check each apple one by one, it takes you
10 steps. If you have 100 apples, it takes you 100 steps. More input means more time. This
is how loops run.

5.1.​Big O notation
The big O notation is how we represent time complexity of loops. It measures how fast a
program runs as input (n) gets larger. It tells us how the number of operations (steps)
grows when (n) increases.

Let’s look more into this in the next sub topic.


​ ​

5.2.​Common Time Complexity Cases in Loops


5.2.1.​O(1) ➜ Constant Time (Super Fast)
This loop runs once or a fixed number of times. It’s notated as O(1)

Here’s an example to help you understand better:


#Still using our apple analogy from earlier.
#Directly grabbing the first apple without checking others

print(“Grab first apple”)

# In this example, our code runs in one step.

Here’s another example:

def get_first_item(arr):
​ return arr[0]

#Even if arr contains 1 million numbers, the function only looks at one item. Therefore, it
always runs in constant time.

5.2.2.​O(n) ➜ Linear Time (Proportional to input Size)


This loop runs once per input item. If there are ten apples to be checked, it takes ten steps
to check each apple.

Let’s visualise this in code format:

for apple in range(n):


​ print(“Checking apple”,apple)

#if we set our value of n to be 3, this loop would run three times.
#Same with if n = 1,000,000. The loop would run 1,000,000 times.
# If n grows, the number of steps grows with it.
5.2.3.​O(n2) ➜Quadratic Time (Super Slow for Large Values of n)
This time complexity is used when a loop runs inside another loop. (Nested
loops) We shall dive deeper into this in the next topic.

Nested loops multiply the number of operations. If n=100, the loop runs 10000 times.

Let’s look at this example:

for i in range(n):
for j in range(n):
​ print( i , j )

#This notation is not good for large numbers or large data.


#Avoid using nested loops in large applications unless necessary.

5.2.4.​O(log n) ➜ Logarithmic Time (Super Efficient)


Instead of checking every item, the loop cuts the work in half each step. Imagine you have
a book with 1,000 pages, and you’re looking for a specific word. You could find the word in
two ways.
●​ Slow way (O(n)): Flip each page one by one until you find it.
●​ Fast way (O(log n)): Open the middle page first, then decide:
○​ If the word is before the middle, search the right half
○​ Repeat until you find the word!
○​ If the word is after the middle, search the left half

In other words, logarithmic time helps us quickly narrow down searches.

​ ​ ​
Here’s a simple example for its usage:
​ ​ ​
n = 32
while n > 1 :
​ print(f”Checking {n}”)
​ n //= 2

#Instead of checking all 32 numbers, we only check 5 times!
​ ​ ​
#The table below displays the output of our code

Checking 32
Checking 16
Checking 8
Checking 4
Checking 2

​ ​ ​

Summary Table

Time Complexity Growth Rate Example

O(1) Constant Time Super Fast Return first item in a list

O(n) Linear Time Grows with input Loop through a list of


numbers

O(n2) Quadratic Time Slows Down Quickly Nested loops in a grid

O(log n) Logarithmic Time Efficient Binary search in sorted


lists

5.3.​Why Time Complexity Matters


If you are writing loops for competitive coding, AI models, big data processing,
understanding time complexity helps optimize speed!

●​ Real time importance of Time complexity


○​ Sorting Large DataSets (O(log n) vs. O(n2))
○​ Database Searching (O(log n) vs. O(n))
○​ Machine Learning and AI

Time complexity is very important in handling edge cases (unusual or extreme inputs
that can cause a program to behave unexpectedly)
5.3.1.​Large Inputs Edge Cases
​ Example: Sorting 10 million elements
​ Solution: Optimize the algorithm (O(n log n) vs. O(n2))

5.3.2.​Infinite Loop Edge Cases


Solution: Ensure loop eventually stops.

5.3.3.​Special Mathematical Cases


Example: Factorial ( 0! = 1) or ( 1/x)
Solution: USe conditional checks for these cases

5.3.4.​Empty Inputs
Solution: Check for empty inputs before proceeding

6.​Nested Loops and Optimization


A nested loop is a loop inside another loop. It allows us to repeat tasks on multiple levels.
For example, nested loops can be used for checking rows and columns in a table or
printing patterns!
Think of a chessboard. There are rows and columns. To check every square, we need two
loops:
●​ One loop for rows
●​ One loop for columns inside rows

​ for row in range(6): # Creates 6 rows
​ ​ for col in range(6): # Creates 6 columns
​ ​ ​ if (row + col) % 2 == 0:
​ ​ ​ ​ print(“⬛”, end=” “) #Black square
​ ​ ​ else:
​ ​ ​ ​ print(“⬜”, end=” ”) #White square
​ ​ print() #Moves to the next line

​ # Visually, the output looks like this



⬛⬜⬛⬜⬛⬜
⬜⬛⬜⬛⬜⬛
⬛⬜⬛⬜⬛⬜
⬜⬛⬜⬛⬜⬛
⬛⬜⬛⬜⬛⬜
⬜⬛⬜⬛⬜⬛

7.​Competitive Coding cases



​ In this part, we’ll explore a few competitive coding cases that involve loops.​

1.​ Print a Pattern
Given (n), print a right-angled triangle of *
Example (n=4)
​ ​ ​

*
**
***
****

​ #Your code should display something similar to the above diagram.


​ #Make sure to use loops in your code

2.​ Reserve a number


​ ​ Given n , reverse its digits using a loop.

​ ​ Example (n = 1234): Output 4321


3.​ Given a number n , find the sum of its digits.
Example (n = 542): Output 🠚 11

8.​Summary
●​ Loops repeat tasks automatically, making programs more efficient.
●​ for loops iterate for a set number of times, while while loops continue until a
condition becomes false.
●​ Break stops a loop early, while continue skips an iteration.
●​ Loop control statements help manage behaviour inside loops.
●​ Optimise time complexity for speed in coding challenges
●​ Avoid inefficient nested loops
●​ Plan for edge cases to ensure robust algorithms

You might also like