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.
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}")
# 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
*
* *
* * *
* * * *
* * * * *
# 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}")
break statement terminates only the immediate inner loop in which it resides. The outer loop continues its remaining iterations unaffected.