sciandu
Computer science

Computer science

Nested loops

A loop inside a loop: this is how rows and columns, patterns and clocks come to life.

What you need first

Look at a clock: for every hour, the minutes run from 0 to 59, then the hour moves on and everything starts over. Many programs work exactly like that: one loop runs, and in each of its passes a second loop runs all the way through. This is called nested loops, and you find them in calendars, screens and game boards.

Rows and columns

Imagine you are drawing a pattern of stars: 3 rows with 5 stars each. The outer loop says: make 3 rows. The inner loop says: draw 5 stars in this row. For every single row, the inner loop runs all the way through once. So the outer loop counts the rows, the inner one counts the columns.

Loop runner
Repetitions3

repeat 3 times:

draw ⭐

draw 🔷

3 × 2 = 6 shapes
Try it: set the repetitions and watch the total number of shapes. Each pass produces 2 shapes, so the total is repetitions times 2, exactly the outer times inner rule.

Total count: outer times inner

How often does the innermost step run in total? Simple: the outer count times the inner count. With 3 rows of 5 stars that is 3 times 5 = 15 stars. On the clock it is 24 hours times 60 minutes = 1440 minutes per day. This multiplication is the key to nested loops.

Common mistakes

Two mistakes happen to almost everyone at first. First: adding outer plus inner instead of multiplying. 3 rows of 5 stars make 15 stars, not 8. Second: forgetting that the inner loop starts over every time. After row 1, the inner loop does not continue at star 6, it starts again at star 1, just in row 2.

Exercises

0 of 6 solved

Time to try it yourself. You can't break anything, every attempt counts.

The outer loop runs 2 times, and in each of its passes the inner loop runs 3 times. How often does the innermost step run in total?

A program draws 3 rows with 5 stars each. How many stars is that in total?

Outer loop: 4 passes. Inner loop: 4 passes. How often does the innermost step run?

Order the loops by the total number of innermost steps, from smallest to largest.

  1. 1outer 5, inner 5
  2. 2outer 4, inner 2
  3. 3outer 3, inner 4
  4. 4outer 2, inner 3

A digital clock counts hours and minutes. Which description matches the nested loops?

You work out the total number of innermost steps by outer and inner.

Where this leads