Loops – Nested Loops

A loop can contain another loop – just as an if-statement can contain another if statement. Nested loops are important in many situations to allow the necessary computation to happen in the correct way.  In this document we focus on doubly nested loops only. While nesting three or more loops is required in some problems, students typically find it harder to abstract and it can get tedious to trace.

This document discusses seven nested loop examples covering a range of nested loop situations. A number of examples relate to previously discussed material. The seven examples include one for Scratch and six for Python. They are:

The following video discusses the motivation of nested loops.

How can you help students master nested loop?

  • Ask students to trace the execution of the loops with pencil and paper – the old-fashioned way
  • Running the program with a small size input in PythonTutor often clarifies what is occurring (or happening).
  • Include print statements so they see the values of variables at each point of the execution

Above all, let students experiment with making changes to the loops and experiment.  It will help them get the experience needed to write correctly nested loops.