IG

IG Math Space

Mathematics Teaching and Research

📚 Classroom Space · Teaching Note

Nested Loops

Module III — Flow Control (c) · A comprehensive classroom teaching note on nested loops, patterns, matrices and 2D data structures with flowcharts and example programs.

👨‍🏫 Gafoor I 🏛️ NAM College Kallikkandy 📐 Department of Mathematics 📘 Taming Python by Programming

📋 Contents

  1. Learning Objectives
  2. Introduction to Nested Loops
  3. How Nested Loops Work
  4. Pattern Programs
  5. Matrix Programs
  6. More Nested Loop Programs
  7. Common Mistakes
  8. Classroom Activities
  9. Review Questions
  10. Summary
01 Learning Objectives

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.
02 Introduction to Nested Loops

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.

💡 Key idea: For each step of the outer loop, the inner loop runs completely — from start to finish.

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
03 How Nested Loops Work

3.1 Execution Order

  1. The outer loop starts and picks its first item.
  2. Control enters the inner loop, which runs completely.
  3. Control returns to the outer loop, which picks its next item.
  4. Steps 2–3 repeat until the outer loop finishes.

3.2 Total Number of Iterations

Total Iterations = (Outer Iterations) × (Inner 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 iInner jPrints
00, 1, 20 0, 0 1, 0 2
10, 1, 21 0, 1 1, 1 2
20, 1, 22 0, 2 1, 2 2

Conceptual Flowchart — Nested Loops

Outer Start Outer Items Remaining? No End Yes Inner Start Inner Items Remaining? No Back to outer Yes Execute Inner Loop Body Inner loop

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)
0 0 0 1 0 2 1 0 1 1 1 2 2 0 2 1 2 2

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
1 * 1 = 1 1 * 2 = 2 1 * 3 = 3 --- 2 * 1 = 2 2 * 2 = 4 2 * 3 = 6 --- 3 * 1 = 3 3 * 2 = 6 3 * 3 = 9 ---
Remember: In a nested while, the inner loop's control variable (j) must be re-initialised before the inner loop each time.
04 Pattern Programs Using Nested Loops

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()
Enter number of rows: 5 * * * * * * * * * * * * * * *

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()
Enter number of rows: 5 * * * * * * * * * * * * * * *

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()
Enter number of rows: 5 * * * * * * * * * * * * * * * * * * * * * * * * *

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()
Enter number of rows: 5 1 1 2 1 2 3 1 2 3 4 1 2 3 4 5

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()
Enter number of rows: 5 1 2 2 3 3 3 4 4 4 4 5 5 5 5 5

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()
Enter number of rows: 5 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15

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()
Enter number of rows: 4 * *** ***** ******* ***** *** *
05 Matrix Programs Using Nested Loops

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()
Enter number of rows: 2 Enter number of columns: 3 Enter element [0][0]: 1 Enter element [0][1]: 2 Enter element [0][2]: 3 Enter element [1][0]: 4 Enter element [1][1]: 5 Enter element [1][2]: 6 The matrix is: 1 2 3 4 5 6

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)
Sum of matrices: [10, 10, 10] [10, 10, 10] [10, 10, 10]

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)
Product of matrices: [19, 22] [43, 50]
💡 Note: Matrix multiplication requires three nested loops — one for each row, one for each column, and one for the dot product.

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)
Transpose: [1, 4] [2, 5] [3, 6]

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)
Sum of all elements: 45
06 More Nested Loop Programs

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()
Table of 1 1 x 1 = 1 1 x 2 = 2 ... 1 x 10 = 10 Table of 2 2 x 1 = 2 2 x 2 = 4 ... 2 x 10 = 20 (and so on up to Table of 5)

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=" ")
Enter N: 30 Prime numbers up to 30 are: 2 3 5 7 11 13 17 19 23 29

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)
Pairs with sum 9 : 2 + 7 = 9 4 + 5 = 9 8 + 1 = 9

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.")
The matrix is symmetric.
07 Common Mistakes to Avoid
MistakeCorrection
Using the same variable for both loopsUse distinct names — i for outer, j for inner
Forgetting to re-initialise the inner loop variable in nested whileReset j = 0 (or j = 1) before the inner loop each time
Incorrect indentationThe inner loop must be indented inside the outer loop
Confusing outer and inner loop rolesOuter → rows; Inner → columns / per-row items
Forgetting print() after the inner loopPrints stay on one line without it
Assuming break exits both loopsbreak exits only the innermost loop
Using range(1, rows) instead of range(1, rows + 1)Remember range stops before the end value
💡 Note: To exit both loops when a condition is met, use a flag variable or a return (inside a function).
08 Classroom Activities

🔍 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.

09 Review Questions
  1. What is a nested loop? Give a real-world example where nested loops are useful.
  2. How many times does the inner loop execute in for i in range(4): for j in range(5):?
  3. 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).
  4. Write a Python program to print a right-angled triangle of stars using nested loops.
  5. Write a Python program to print a pyramid pattern of stars.
  6. Write a Python program to print Floyd's triangle up to N rows.
  7. Write a Python program to add two 3×3 matrices using nested loops.
  8. Write a Python program to multiply two 2×2 matrices using nested loops.
  9. How can you exit both loops of a nested structure when a condition is met?
  10. Explain why break inside a nested loop only terminates the inner loop.
10 Summary
🧱
DefinitionA loop inside another loop. Inner loop runs completely for each outer iteration.
📐
Iteration CountTotal iterations = (outer count) × (inner count).
🔄
Execution OrderOuter picks an item → inner runs fully → outer picks next → repeat.
PatternsOuter loop controls rows; inner loop controls what appears in each row.
📊
MatricesOuter loop traverses rows; inner loop traverses columns. Multiplication needs 3 nested loops.
⚠️
Common PitfallIn nested while, always re-initialise the inner loop variable before the inner loop.
G

Gafoor I

Assistant Professor  |  Department of Mathematics  |  NAM College Kallikkandy

Teaching Note · Module III (c) · Nested Loops in Python · Academic Year 2025–26