A times table with nested loops
Print a multiplication table with two loops, one inside the other: the outer loop chooses the row, the inner loop goes along it. Change the size of the table, count the products, and see how the inner loop starts again on every row.
Core concept
In nested loops the inner loop runs all the way through for every turn of the outer loop, so a table of r rows and c columns has r × c products
Topic: Loops and patterns
A times table has rows and columns. Row 3, column 4 holds 3 × 4 = 12. To print it, a program uses two loop: Steps that repeat, either a set number of times or until something becomes true. All key words, one inside the other. The outer loop counts the rows: row = 1, 2, 3 … For each row, the inner loop counts along the columns, col = 1, 2, 3, 4, and writes row × col each time. When the inner loop has finished, the program starts a new line, and the outer loop moves to the next row, where the inner loop starts again from col = 1. So the inner loop's body runs rows × columns times in all.
What you will learn
- Trace the counters of an outer and an inner loop.
- Explain why the inner loop starts again on every row.
- Work out how many times the inner loop's body runs.
- Change a loop's range to print a different table.
Before you start
- Know for loops and the times tables.
Materials
- A notebook to copy the table
Equipment
- None
Procedure
- Run the program for 3 rows and 4 columns.
- Step through it and watch row and col change.
- Make the biggest table, 5 by 5, and run it.
- Answer the practice challenges.