📋 Contents
By the end of this class session, students will be able to:
- Understand the concept of a nested loop and how it differs from a simple loop.
- Trace the execution order of nested loops — outer loop vs inner loop.
- Compute the total number of iterations as outer × inner.
- Construct pattern-printing programs using nested loops.
- Perform matrix operations (addition, traversal) using nested loops.
- Use nested loops for 2D data structures such as tables and grids.
- Recognize common errors and choose appropriate loop variable names.
2.1 Definition
A nested loop is a loop placed inside another loop. The inner loop completes all its iterations for each single iteration of the outer loop.
2.2 Why do we need nested loops?
Many real-world problems involve two or more dimensions:
- Rows and columns of a table
- Matrices in mathematics
- Grid-based games (chess, tic-tac-toe)
- Pixel positions on a screen (x, y)
- Star and number patterns
A single loop can only walk a 1D list. For 2D data, we need one loop per dimension — hence a loop inside a loop.
2.3 Syntax
Using for loops:
for outer_var in outer_sequence:
for inner_var in inner_sequence:
statement(s)
Using while loops:
while outer_condition:
while inner_condition:
statement(s)
Mixed form (a for inside a while, or vice versa) is also valid:
for i in range(3):
j = 0
while j < 3:
print(i, j)
j += 1
3.1 Execution Order
- The outer loop starts and picks its first item.
- Control enters the inner loop, which runs completely.
- Control returns to the outer loop, which picks its next item.
- Steps 2–3 repeat until the outer loop finishes.
3.2 Total Number of Iterations
For example, for i in range(3): for j in range(4): executes the inner body 3 × 4 = 12 times.
3.3 Trace Example
Consider the following code:
for i in range(3):
for j in range(3):
print(i, j)
Trace:
| Outer i | Inner j | Prints |
|---|---|---|
| 0 | 0, 1, 2 | 0 0, 0 1, 0 2 |
| 1 | 0, 1, 2 | 1 0, 1 1, 1 2 |
| 2 | 0, 1, 2 | 2 0, 2 1, 2 2 |
Conceptual Flowchart — Nested Loops
Fig 1. Flowchart of nested loops — inner loop completes fully for each outer iteration.
3.4 Simple Example — 2D Coordinates
for i in range(3):
for j in range(3):
print(i, j)
Explanation: For each value of i (0, 1, 2), the inner loop runs for j = 0, 1, 2. Total iterations = 3 × 3 = 9.
3.5 Nested while Loop Example
i = 1
while i <= 3:
j = 1
while j <= 3:
print(i, "*", j, "=", i * j)
j += 1
print("---")
i += 1
while, the inner loop's control variable (j) must be re-initialised before the inner loop each time.Nested loops are the classic tool for printing patterns. The outer loop controls the number of rows; the inner loop controls what is printed in each row.
Example 1: Right-angled triangle of stars
rows = int(input("Enter number of rows: "))
for i in range(1, rows + 1):
for j in range(i):
print("*", end=" ")
print()
Example 2: Inverted right-angled triangle
rows = int(input("Enter number of rows: "))
for i in range(rows, 0, -1):
for j in range(i):
print("*", end=" ")
print()
Example 3: Pyramid pattern
rows = int(input("Enter number of rows: "))
for i in range(1, rows + 1):
for j in range(rows - i):
print(" ", end=" ")
for k in range(2 * i - 1):
print("*", end=" ")
print()
Example 4: Number triangle
rows = int(input("Enter number of rows: "))
for i in range(1, rows + 1):
for j in range(1, i + 1):
print(j, end=" ")
print()
Example 5: Same number in each row
rows = int(input("Enter number of rows: "))
for i in range(1, rows + 1):
for j in range(1, i + 1):
print(i, end=" ")
print()
Example 6: Floyd's Triangle
rows = int(input("Enter number of rows: "))
num = 1
for i in range(1, rows + 1):
for j in range(1, i + 1):
print(num, end=" ")
num += 1
print()
Example 7: Diamond pattern
rows = int(input("Enter number of rows: "))
# Upper half
for i in range(1, rows + 1):
for j in range(rows - i):
print(" ", end="")
for k in range(2 * i - 1):
print("*", end="")
print()
# Lower half
for i in range(rows - 1, 0, -1):
for j in range(rows - i):
print(" ", end="")
for k in range(2 * i - 1):
print("*", end="")
print()
Matrices are natural 2D structures. Rows are controlled by the outer loop; columns by the inner loop.
Example 8: Read and print a matrix
rows = int(input("Enter number of rows: "))
cols = int(input("Enter number of columns: "))
matrix = []
for i in range(rows):
row = []
for j in range(cols):
val = int(input(f"Enter element [{i}][{j}]: "))
row.append(val)
matrix.append(row)
print("\nThe matrix is:")
for i in range(rows):
for j in range(cols):
print(matrix[i][j], end=" ")
print()
Example 9: Matrix addition (3×3)
A = [[1, 2, 3],
[4, 5, 6],
[7, 8, 9]]
B = [[9, 8, 7],
[6, 5, 4],
[3, 2, 1]]
C = [[0, 0, 0],
[0, 0, 0],
[0, 0, 0]]
for i in range(3):
for j in range(3):
C[i][j] = A[i][j] + B[i][j]
print("Sum of matrices:")
for row in C:
print(row)
Example 10: Matrix multiplication (2×2)
A = [[1, 2], [3, 4]]
B = [[5, 6], [7, 8]]
C = [[0, 0], [0, 0]]
for i in range(2):
for j in range(2):
for k in range(2):
C[i][j] += A[i][k] * B[k][j]
print("Product of matrices:")
for row in C:
print(row)
Example 11: Transpose of a matrix
A = [[1, 2, 3], [4, 5, 6]]
T = [[0, 0], [0, 0], [0, 0]]
for i in range(2):
for j in range(3):
T[j][i] = A[i][j]
print("Transpose:")
for row in T:
print(row)
Example 12: Sum of all elements in a matrix
A = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
total = 0
for i in range(3):
for j in range(3):
total += A[i][j]
print("Sum of all elements:", total)
Example 13: Multiplication tables from 1 to 5
for i in range(1, 6):
print("Table of", i)
for j in range(1, 11):
print(i, "x", j, "=", i * j)
print()
Example 14: Find all prime numbers up to N
n = int(input("Enter N: "))
print("Prime numbers up to", n, "are:")
for num in range(2, n + 1):
is_prime = True
for i in range(2, int(num ** 0.5) + 1):
if num % i == 0:
is_prime = False
break
if is_prime:
print(num, end=" ")
Example 15: Print all pairs (i, j) whose sum is a target
numbers = [2, 4, 3, 5, 7, 8, 1]
target = 9
print("Pairs with sum", target, ":")
for i in range(len(numbers)):
for j in range(i + 1, len(numbers)):
if numbers[i] + numbers[j] == target:
print(numbers[i], "+", numbers[j], "=", target)
Example 16: Check whether a matrix is symmetric
A = [[1, 2, 3],
[2, 5, 6],
[3, 6, 9]]
symmetric = True
for i in range(3):
for j in range(3):
if A[i][j] != A[j][i]:
symmetric = False
break
if symmetric:
print("The matrix is symmetric.")
else:
print("The matrix is not symmetric.")
| Mistake | Correction |
|---|---|
| Using the same variable for both loops | Use distinct names — i for outer, j for inner |
Forgetting to re-initialise the inner loop variable in nested while | Reset j = 0 (or j = 1) before the inner loop each time |
| Incorrect indentation | The inner loop must be indented inside the outer loop |
| Confusing outer and inner loop roles | Outer → rows; Inner → columns / per-row items |
Forgetting print() after the inner loop | Prints stay on one line without it |
Assuming break exits both loops | break exits only the innermost loop |
Using range(1, rows) instead of range(1, rows + 1) | Remember range stops before the end value |
return (inside a function).🔍 Activity 1 — Predict the Output
What will the following code print? Work it out on paper first, then verify.
for i in range(1, 4):
for j in range(1, i + 1):
print(i * j, end=" ")
print()
🐛 Activity 2 — Debug the Code
Find and fix the error in the code below:
rows = 3
i = 1
while i <= rows:
j = 1
while j <= rows:
print("*", end=" ")
print()
i += 1
Hint: What must happen to j inside the inner loop?
✏️ Activity 3 — Write the Program
Write a Python program using nested loops that:
- Accepts a number N from the user.
- Prints an N × N square of stars.
- Then prints a lower triangular pattern of stars.
🧩 Activity 4 — Pattern Challenge
Write nested loops to print the following number pattern:
1 2 3 4 5 6 7 8 9 10
Hint: Use a separate counter variable that increments after each print.
📊 Activity 5 — Matrix Task
Given A = [[1, 2], [3, 4]] and B = [[5, 6], [7, 8]], write a nested loop program to compute and print A + B and A × B.
- What is a nested loop? Give a real-world example where nested loops are useful.
- How many times does the inner loop execute in
for i in range(4): for j in range(5):? - Explain the execution order of a nested loop with a trace of
for i in range(2): for j in range(3): print(i, j). - Write a Python program to print a right-angled triangle of stars using nested loops.
- Write a Python program to print a pyramid pattern of stars.
- Write a Python program to print Floyd's triangle up to N rows.
- Write a Python program to add two 3×3 matrices using nested loops.
- Write a Python program to multiply two 2×2 matrices using nested loops.
- How can you exit both loops of a nested structure when a condition is met?
- Explain why
breakinside a nested loop only terminates the inner loop.
while, always re-initialise the inner loop variable before the inner loop.Gafoor I
Assistant Professor | Department of Mathematics | NAM College Kallikkandy
Teaching Note · Module III (c) · Nested Loops in Python · Academic Year 2025–26