Lecture Notes - Nested Loop (with Activiies)
Lecture Notes - Nested Loop (with Activiies)
1. Introduction to Loops
A loop is a programming construct that repeats a block of code as long as a condition is met. In
Python, we have two types of loops:
A nested loop is a loop inside another loop. The "outer" loop controls the overall repetition,
and the "inner" loop executes fully for every iteration of the outer loop. Nested loops can be
helpful when dealing with multidimensional data (like matrices or grids) or performing repeated
actions across multiple layers of iteration.
In Python, a nested loop follows the same syntax as a regular loop, but with an additional loop
inside the first one.
Output:
i: 0, j: 0
i: 0, j: 1
i: 1, j: 0
i: 1, j: 1
i: 2, j: 0
i: 2, j: 1
Here, the outer loop runs 3 times, and for each iteration of the outer loop, the inner loop runs 2
times.
Output:
*****
*****
*****
*****
*****
Nested loops can also use while loops inside another while loop. The syntax is similar to for
loops.
Example:
i=0
while i < 3: # Outer loop
j=0
while j < 2: # Inner loop
print(f"i: {i}, j: {j}")
j += 1
i += 1
Output:
i: 0, j: 0
i: 0, j: 1
i: 1, j: 0
i: 1, j: 1
i: 2, j: 0
i: 2, j: 1
The time complexity of nested loops depends on the number of iterations in each loop. For
example, if the outer loop runs mmm times and the inner loop runs n times, the total time
complexity will be O(m×n).
Example 2: Outer loop runs nnn times, and inner loop also runs nnn times:
2
o Time complexity: O(n ) (quadratic time)
Write a program to print the multiplication table for a number n (up to 10). For example, if the
input is 3, it should print the following:
1*3=3
2*3=6
NMF1- Introduction to Programming
Topic: Nested Loops
3*3=9
...
10 * 3 = 30
Write a program that prints a number pattern in the following format for n = 5:
1
12
123
1234
12345
Matrix A:
12
34
Matrix B:
56
78
Resulting Matrix:
68
10 12
Important:
Break and Continue: You can use break to exit a loop early or continue to skip the
current iteration and move to the next.
Avoid Deep Nesting: Too many nested loops can make the code harder to read and may
lead to performance issues. Try to refactor or optimize if possible.
Summary
A nested loop is a loop inside another loop. The inner loop executes for each iteration of
the outer loop.
Nested loops are useful for working with multi-dimensional data or performing repeated
actions.
The time complexity of nested loops is the product of the number of iterations of the
outer and inner loops.
NMF1- Introduction to Programming
Topic: Nested Loops
Practice with nested loops to get comfortable working with complex repetitive tasks.
Additional Resources