On this page11 sections
Lecture 022: Nested Loops
| Day | 8: Loops |
| Lecture | 022 of 057 |
| Estimated video length | 12 min |
| Target | Dart 3.12 |
| Level | Beginner |
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
for (var i = 1; i <= 3; i++) {
for (var j = 1; j <= 2; j++) {
print('i=$i, j=$j');
}
}Output
i=1, j=1
i=1, j=2
i=2, j=1
i=2, j=2
i=3, j=1
i=3, j=2For 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:
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
grid[0][0] = 1
grid[0][1] = 2
grid[0][2] = 3
grid[1][0] = 4
grid[1][1] = 5
grid[1][2] = 63. Patterns
Build up one line in the inner loop, then print it in the outer loop:
for (var row = 1; row <= 4; row++) {
var line = '';
for (var col = 1; col <= row; col++) {
line += '* ';
}
print(line);
}Output
*
* *
* * *
* * * *The inner loop's limit is row, so each line is one star longer than the last.
4. A Multiplication Table
for (var a = 1; a <= 3; a++) {
var line = '';
for (var b = 1; b <= 3; b++) {
line += '${a * b}'.padLeft(4);
}
print(line);
}Output
1 2 3
2 4 6
3 6 9padLeft(4) adds spaces in front so every number takes 4 characters and the columns line up.
Code Examples
Example 1: Class Results
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
Ali: total 253, average 84.3
Sara: total 259, average 86.3
Hamza: total 207, average 69.0
Highest single mark: 92 by SaraLecture 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
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
- How many times does the inner body run in
for (i < 4) { for (j < 5) { ... } }(both starting at 0)? - Change the star pattern so the first line has 4 stars and the last has 1.
- Write nested loops that print every value of
[[1, 2], [3, 4]]. - Where should
totalbe declared to get one total per row of a 2-D list? - Why is naming both counters
ia bad idea?
Practice Answers
- 4 × 5 = 20 times.
- Make the outer loop count down:
for (var row = 4; row >= 1; row--).
var g = [[1, 2], [3, 4]];
for (var row in g) {
for (var value in row) {
print(value);
}
}- Inside the outer loop, before the inner loop.
- The inner
ihides 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.