CodeBlanks Logo Icon CodeBlanks

Summary - Loops

Combine for, while and for-in to write a multiplication table.

Summary - Loops

In this group you learned for, while, do-while, for-in and break/continue. Now we will combine them to print a multiplication table.

The multiplication table is built by counting 1 to 5 with a for loop and writing 2 x i = (2*i) on each line. This structure combines repeated computation with formatted output.

Plan

We will build the multiplication table step by step: (1) count 1 to 5 with for (var i = 1; i <= 5; i++); (2) on each iteration write a line with print("2 x $i = ${2 * i}");; (3) interpolation embeds both i and 2 * i.

This structure is the skeleton of a real calendar or report app too. The loop + interpolation combo is the base of programs that produce screen output. Changing the number lets you build the 3-times or 4-times table easily.

Practice Multiplication table

Build a for (var i = 1; i <= 5; i++) loop. In the body print each line with print("2 x $i = ${2 * i}");. The output must be 5 lines: 2 x 1 = 2, 2 x 2 = 4, 2 x 3 = 6, 2 x 4 = 8, 2 x 5 = 10 (one product per line).

Starter code

main.dart
// Print the 2-times table with a for loop

Sample solution

main.dart
for (var i = 1; i <= 5; i++) {
  print("2 x $i = ${2 * i}");
}

Expected output

2 x 1 = 2
2 x 2 = 4
2 x 3 = 6
2 x 4 = 8
2 x 5 = 10

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 Which loop best fits the 2-times table (1-5)?

main.dart
// multiplication table
  • while
  • for Correct answer
  • do-while
  • if

Explanation: for is the best fit for a counted range.

2 Complete the for header

Question
for (____) {
  print("2 x $i = ${2 * i}");
}
Answer
for (var i = 1; i <= 5; i++) {
  print("2 x $i = ${2 * i}");
}

Explanation: The for header counting 1 to 5 is complete.

All lessons in Beginner