On this page11 sections
  1. Prerequisites
  2. Learning Objectives
  3. 1. A Loop Inside a Loop
  4. 2. Going Through a 2-D List
  5. 3. Patterns
  6. 4. A Multiplication Table
  7. Code Examples
  8. Common Beginner Mistakes
  9. Practice Questions
  10. Practice Answers
  11. Key Takeaways

Lecture 022: Nested Loops

Day8: Loops
Lecture022 of 057
Estimated video length12 min
TargetDart 3.12
LevelBeginner

A clock's minute hand goes all the way round for every single step of the hour hand. A nested loop works the same way: an inner loop runs completely for every round of an outer loop. That's how you go through rows and columns, draw patterns and build tables.

Contents

Prerequisites · Objectives · Lesson · Code Examples · Common Mistakes · Practice Questions · Answers · Takeaways


Prerequisites

Lectures 012 (2-D lists) and 020–021 (loops).


Learning Objectives

  • Trace how a nested loop runs, round by round
  • Count how many times the inner body runs
  • Go through every cell of a 2-D list
  • Draw text patterns with nested loops
  • Use clear names for the outer and inner counters

1. A Loop Inside a Loop

dart
for (var i = 1; i <= 3; i++) {
  for (var j = 1; j <= 2; j++) {
    print('i=$i, j=$j');
  }
}

Output

code
i=1, j=1
i=1, j=2
i=2, j=1
i=2, j=2
i=3, j=1
i=3, j=2

For each value of i, j runs all the way from 1 to 2. The inner body runs 3 × 2 = 6 times in total.

2. Going Through a 2-D List

The outer loop picks the row, the inner loop picks each column in that row:

dart
var grid = [
  [1, 2, 3],
  [4, 5, 6],
];
for (var r = 0; r < grid.length; r++) {
  for (var c = 0; c < grid[r].length; c++) {
    print('grid[$r][$c] = ${grid[r][c]}');
  }
}

Output

code
grid[0][0] = 1
grid[0][1] = 2
grid[0][2] = 3
grid[1][0] = 4
grid[1][1] = 5
grid[1][2] = 6

3. Patterns

Build up one line in the inner loop, then print it in the outer loop:

dart
for (var row = 1; row <= 4; row++) {
  var line = '';
  for (var col = 1; col <= row; col++) {
    line += '* ';
  }
  print(line);
}

Output

code
*
* *
* * *
* * * *

The inner loop's limit is row, so each line is one star longer than the last.

4. A Multiplication Table

dart
for (var a = 1; a <= 3; a++) {
  var line = '';
  for (var b = 1; b <= 3; b++) {
    line += '${a * b}'.padLeft(4);
  }
  print(line);
}

Output

code
   1   2   3
   2   4   6
   3   6   9

padLeft(4) adds spaces in front so every number takes 4 characters and the columns line up.


Code Examples

Example 1: Class Results

dart
void main() {
  var names = ['Ali', 'Sara', 'Hamza'];
  var marks = [
    [78, 85, 90],
    [92, 88, 79],
    [65, 70, 72],
  ];

  for (var s = 0; s < names.length; s++) {
    var total = 0;
    for (var m in marks[s]) {
      total += m;
    }
    var average = total / marks[s].length;
    print('${names[s]}: total $total, average ${average.toStringAsFixed(1)}');
  }

  var best = 0;
  var bestName = '';
  for (var s = 0; s < marks.length; s++) {
    for (var m in marks[s]) {
      if (m > best) {
        best = m;
        bestName = names[s];
      }
    }
  }
  print('Highest single mark: $best by $bestName');
}

Output

code
Ali: total 253, average 84.3
Sara: total 259, average 86.3
Hamza: total 207, average 69.0
Highest single mark: 92 by Sara

Lecture 012 added up one student's marks by hand. Here, the outer loop goes through students and the inner loop through their marks. total is reset at the start of each student's round, inside the outer loop but before the inner one.


Common Beginner Mistakes

1. Reusing the same counter name

dart
for (var i = 1; i <= 2; i++) {
  for (var i = 1; i <= 2; i++) {
    print(i);
  }
}

It runs (printing 1 2 1 2), but inside the inner loop the outer i is hidden, so you can't use it there. Give each loop its own name: row/col, r/c, i/j.

2. Resetting a total in the wrong place: put it before the outer loop for one grand total, or inside the outer loop (before the inner one) for one total per row.

3. Printing inside the inner loop by accident: for patterns, build the line in the inner loop and print it after the inner loop ends. Otherwise every star lands on its own line.

4. Forgetting how fast it grows: 1000 × 1000 is a million rounds. Nested loops over big lists can get slow.


Practice Questions

  1. How many times does the inner body run in for (i < 4) { for (j < 5) { ... } } (both starting at 0)?
  2. Change the star pattern so the first line has 4 stars and the last has 1.
  3. Write nested loops that print every value of [[1, 2], [3, 4]].
  4. Where should total be declared to get one total per row of a 2-D list?
  5. Why is naming both counters i a bad idea?

Practice Answers

  1. 4 × 5 = 20 times.
  2. Make the outer loop count down: for (var row = 4; row >= 1; row--).
dart
var g = [[1, 2], [3, 4]];
for (var row in g) {
  for (var value in row) {
    print(value);
  }
}
  1. Inside the outer loop, before the inner loop.
  2. The inner i hides the outer one, so the inner loop can't read the row number.

Key Takeaways

  • The inner loop runs completely for every round of the outer loop.
  • Total inner rounds = outer count × inner count.
  • Outer loop = rows, inner loop = columns, for 2-D lists and tables.
  • Build a line in the inner loop, print it in the outer loop.
  • Use different, meaningful names for each counter.