Count Controlled Iteration (For Loops)
A nested loop is a for loop written inside the body of another for loop. The outer loop controls the larger job and the inner loop carries out a smaller job for each step of it. The inner loop completes all of its repetitions before the outer loop moves on to its next repetition, so the two loops never run side by side.
If the outer loop repeats 3 times and the inner loop repeats 5 times, the inner loop's body runs 3 × 5 = 15 times. Following the loop variables makes this easy to see: the outer loop variable stays fixed while the inner loop variable counts all the way through, then it starts again from its first value.
| Outer loop variable | Inner loop variable counts | Inner loop body runs |
|---|---|---|
| 1 | 1, 2, 3, 4, 5 | 5 times |
| 2 | 1, 2, 3, 4, 5 | 5 times |
| 3 | 1, 2, 3, 4, 5 | 5 times |
In the program below the outer loop picks a row of the hall and the inner loop visits each seat in that row, so every seat is labelled exactly once.
# Labels every seat in a hall with 3 rows of 5 seats
for row in range(1, 4):
for seat in range(1, 6):
print("Row " + str(row) + " seat " + str(seat))Output:
Row 1 seat 1
Row 1 seat 2
Row 1 seat 3
Row 1 seat 4
Row 1 seat 5
Row 2 seat 1
Row 2 seat 2
Row 2 seat 3
Row 2 seat 4
Row 2 seat 5
Row 3 seat 1
Row 3 seat 2
Row 3 seat 3
Row 3 seat 4
Row 3 seat 5
A two-dimensional data structure stores data in rows and columns, like a table. In a table of records, each row is one record and each column is a field. Nested loops are ideal for this because they can process every field in every record: the outer loop traverses the records, working down the table one row at a time, and the inner loop traverses the fields in that record, working across the row. Because the inner loop restarts for each new record, every field in that record is processed before moving to the next record.
Edexcel GCSE Computer Science · Count Controlled Iteration (For Loops)
Edexcel GCSE Computer Science · Two-dimensional Arrays (2D Lists)