Python Nested Loops: Matrix Traversal, Pattern Printing & Algorithms

A nested loop is a loop placed inside the body of an outer loop. In computer science, nested loops are essential for working with multidimensional data structures (such as 2D tables, images, and matrices) and solving university exam pattern printing problems.


1. Execution Flow of Nested Loops

For each single iteration of the outer loop, the inner loop executes through all its iterations from start to finish:

for i in range(1, 4):      # Outer loop runs 3 times (i = 1, 2, 3)
    for j in range(1, 3):  # Inner loop runs 2 times per outer loop
        print(f"i = {i}, j = {j}")

2. Classic BCA Exam Pattern: Right-Angled Star Triangle

# Program: Print Star Pattern
rows = 5

for i in range(1, rows + 1):
    for j in range(1, i + 1):
        print("*", end=" ")
    print()  # Newline after each row

Output:

* 
* * 
* * * 
* * * * 
* * * * * 

3. Working with 2D Matrices (Grids)

# Traversing a 3x3 Matrix:
matrix = [
    [10, 20, 30],
    [40, 50, 60],
    [70, 80, 90]
]

for row_index, row in enumerate(matrix):
    for col_index, value in enumerate(row):
        print(f"matrix[{row_index}][{col_index}] = {value}")

Frequently Asked Questions (FAQ)

Does a break statement inside an inner loop exit the outer loop?

No. A break statement terminates only the immediate inner loop in which it resides. The outer loop continues its remaining iterations unaffected.
Share Share on Facebook Share on Twitter Share on LinkedIn Pin on Pinterest Share on Stumbleupon Share on Tumblr Share on Reddit Share on Diggit

You may also like this!