Loop within a Loop, Nested Loops
When developing a program, there are situations where you need to use a loop inside another loop.
For example, when processing table data consisting of rows and columns or printing complex patterns, you need more than one loop.
This structure, where one loop contains another loop, is called nested loops
.
In this lesson, we will explore what nested loops are, with simple examples and use cases in programming.
When do we use nested loops?
Using nested loops makes it easy to handle structures like 2D arrays (matrices) or tables.
For example, let's write a program that prints a rectangle composed of asterisks (*).
# Number of rows
rows = 3
# Number of columns
cols = 5
for i in range(rows): # Outer loop: row iteration
for j in range(cols): # Inner loop: column iteration
print("*", end="") # Print asterisks in the same line
print() # Line break after each row
This code prints a rectangle with 3 rows and 5 columns as shown below.
The outer for
loop handles the row iteration, and the inner for
loop handles the column iteration.
*****
*****
*****
In the code, i
is the variable used by the outer loop, and j
is the variable used by the inner loop.
In the outer loop, i
increments from 0 to 2, executing the inner loop.
In the inner loop, j
increments from 0 to 4, printing an asterisk 5 times.
After a row is completed, the value of i
increases by 1, and the inner loop executes again to print the next row.
When i
becomes 2, the outer loop terminates, and the program ends.
Use cases in programming
Nested loops are used in various programming scenarios.
Let's look at an example of printing multiplication tables to see the use case of nested loops.
Printing Multiplication Tables
The code below prints the results of multiplying numbers from each table 2 through 9 by 1 through 9.
# Iterate through tables 2 to 9
for i in range(2, 10):
# Multiply each table by numbers 1 to 9
for j in range(1, 10):
# Print the result
print(f"{i} x {j} = {i*j}")
# Line break after each table
print()
This code calculates and prints each table's results, producing the following output:
2 x 1 = 2
2 x 2 = 4
2 x 3 = 6
2 x 4 = 8
2 x 5 = 10
2 x 6 = 12
2 x 7 = 14
2 x 8 = 16
2 x 9 = 18
3 x 1 = 3
3 x 2 = 6
3 x 3 = 9
...(skipped)...
9 x 7 = 63
9 x 8 = 72
9 x 9 = 81
Want to learn more?
Join CodeFriends Plus membership or enroll in a course to start your journey.