Skip to content
ExamSpine

Lesson 3.7

Nested loops

Part 3: RepetitionReading, about 5 min3 exercises in this lesson, in Python2 exercises in this lesson, in Java

Java answers can't run on Spine yet. You can still read Java, trace it, and put an answer's lines in order.

Nested loops

By the end of this you will be able to put one loop inside another to work through a grid, row by row and column by column, and say how many times each line runs.

A nested loop is a loop inside another loop. The inner loop runs all of its turns for every single turn of the outer loop. A grid is the natural fit: the outer loop goes through the rows, and for each row the inner loop goes through the columns.

A nested loop

This program draws a small board of 3 rows and 5 columns, where the squares take turns between # and ., like a chessboard.

for row in range(3):
    line = ""
    for col in range(5):
        if (row + col) % 2 == 0:
            line = line + "#"
        else:
            line = line + "."
    print(line)
public static void main(String[] args) {
    for (int row = 0; row < 3; row++) {
        String line = "";
        for (int col = 0; col < 5; col++) {
            if ((row + col) % 2 == 0) {
                line = line + "#";
            } else {
                line = line + ".";
            }
        }
        System.out.println(line);
    }
}

It prints:

#.#.#
.#.#.
#.#.#

Each square depends on both counters. When row + col is even, the square is #. When it is odd, the square is a dot (.). That is why the middle row starts with .: there row is 1, so the first square has row + col equal to 1.

How the counters move

The inner counter starts again at 0 on every turn of the outer loop. It does not carry on from where it stopped.

rowcol takesThe line printed
00, 1, 2, 3, 4#.#.#
10, 1, 2, 3, 4.#.#.
20, 1, 2, 3, 4#.#.#

Read the table down: row changes slowly, once per line. Read along a row: col changes fast, once per square.

Where each line goes

Where a line sits decides how often it runs. In the board program:

  • line = "" is inside the outer loop but before the inner loop, so each row starts with an empty line. It runs 3 times, once per row.
  • The if and its two joins are inside the inner loop, so one of the joins runs for every square: 3 times 5, which is 15 times.
  • The print is inside the outer loop but after the inner loop, so it prints each row once the row is complete. It runs 3 times.

If line = "" were moved above both loops, the line would never be emptied, so each print would show every square so far, not just one row. If the print were moved into the inner loop, it would run once per square, and show the row growing one square at a time.

How to count the turns

When the inner loop always takes the same number of turns, multiply. An outer loop of 3 turns with an inner loop of 5 turns runs the inner body 3 times 5 = 15 times in total.

Give each loop its own counter

The outer and inner loops need counters with different names, such as row and col. In Java, giving the inner counter the same name as the outer one does not compile, because the outer counter's name is still in use inside the outer loop. In Python it runs, but the inner loop overwrites the outer counter, so a line after the inner loop that uses the outer counter can see the inner loop's last value instead of the row number.

Now try it yourself on the questions below.

Exercise 3.7.1 · Trace itTrace: nested grid

Complete the trace table for this Python code. [2]

Line 1: for r in range(2):
Line 2, indented 1 level: for c in range(3):
Line 3, indented 2 levels: print(r, c)

Fill in one row each time a line changes r or c, or prints something. The table already has the right number of rows. In each row, write only what that line changes; you can leave the other cells empty or copy their values down. Write values the way Python shows them: 3 and 3.0 are different, and text goes in quotes. In the output column, write exactly what appears on screen, with no quotes around it.

Rowrcoutput
1
2
3
4
5
6
7
8
9
10
11
12
13
14

Exercise 3.7.23.7.1 · Write itStar rectangle

Write a program that reads a number of rows and a number of columns, and prints a rectangle of * characters.

  1. Read the number of rows on the first line and the number of columns on the second line.
  2. Print that many rows, each containing that many * characters.
  3. Each row is on its own line. No spaces between the stars.

Both numbers are always whole numbers from 1 to 20. Your program is run several times. Only what it prints is checked.

Running Java here comes later. You can put this answer's lines in order instead. You can still write your Java answer (it stays while this page is open) and compare it with our worked solution. Or try this exercise in Python.

Examples

Your program is run 6 times: the 3 examples below, and 3 hidden ones that check the rules above. Only what it prints is checked.

  • 3 rows of 4 stars (rules 2 and 3)

    You type

    1. typed: 3
    2. typed: 4

    It prints

    ****
    ****
    ****
  • one row of 5 stars (rule 2)

    You type

    1. typed: 1
    2. typed: 5

    It prints

    *****
  • a square (rule 2)

    You type

    1. typed: 2
    2. typed: 2

    It prints

    **
    **
solution.pySolution.java

Exercise 3.7.33.7.2 · Write itGrid coordinates

Write a program that reads a number of rows and a number of columns, and prints every coordinate in the grid, row by row, starting from 0.

  1. Read the number of rows on the first line and the number of columns on the second line.
  2. For each row from 0 up to rows minus 1, and for each column from 0 up to cols minus 1, print the row number, then a comma with no spaces, then the column number.
  3. Print one coordinate per line.
  4. Visit all columns of a row before moving to the next row.

Both numbers are always whole numbers from 1 to 20. Your program is run several times. Only what it prints is checked.

Running Java here comes later. You can put this answer's lines in order instead. You can still write your Java answer (it stays while this page is open) and compare it with our worked solution. Or try this exercise in Python.

Examples

Your program is run 6 times: the 3 examples below, and 3 hidden ones that check the rules above. Only what it prints is checked.

  • a 2 by 3 grid (rules 2 and 4)

    You type

    1. typed: 2
    2. typed: 3

    It prints

    0,0
    0,1
    0,2
    1,0
    1,1
    1,2
  • one row, two columns (rule 2)

    You type

    1. typed: 1
    2. typed: 2

    It prints

    0,0
    0,1
  • three rows, one column (rule 2)

    You type

    1. typed: 3
    2. typed: 1

    It prints

    0,0
    1,0
    2,0
solution.pySolution.java