Skip to content
Programming Loops and patterns
All classes Advanced About 20 min Premium

Star patterns with nested loops

Run two loops, one inside the other, to print a triangle of stars. Change the number of rows, count how many times the inner loop runs, and work out how to turn the triangle into a square.

Core concept

In nested loops the inner loop runs completely for every turn of the outer loop; when the inner loop goes from 1 to row, row r prints r stars and n rows print n(n + 1)/2 stars

Topic: Loops and patterns

A loop: Steps that repeat, either a set number of times or until something becomes true. All key words repeats some lines. A nested loop is a loop inside another loop: for each turn of the outer loop, the inner loop runs all the way through. Think of a clock: for every hour the minute hand goes round 60 times. To print a triangle, the outer loop counts the rows (row = 1 to n) and the inner loop prints the stars in that row (col = 1 to row). Row 1 gets 1 star, row 2 gets 2, and so on, so n rows hold 1 + 2 + … + n = n(n + 1)/2 stars. Change what the inner loop counts to and the shape changes: counting to n every time makes a square of n × n stars.

Key words explained

What you will learn

  • Trace a nested loop and say how many times the inner loop runs in each row.
  • Count the total runs of the inner loop: n(n + 1)/2 for a triangle, n × n for a square.
  • Change a loop's bounds to change the pattern.
  • Write the lines of a nested loop in order.

Before you start

  • Know for loops and how a counter changes.

Materials

  • A notebook to draw the patterns

Equipment

  • None

Procedure

  1. Run the program with 4 rows and look at the pattern.
  2. Step through it and watch row and col change.
  3. Try 6 rows and count the stars.
  4. Answer the practice challenges.
Premium experiment Create a free account