On this page14 sections
  1. Prerequisites
  2. Learning Objectives
  3. 1. The for Loop
  4. 2. Shortcut Operators
  5. 3. Looping Over a List by Index
  6. 4. for-in: Each Item, No Index
  7. 5. forEach
  8. 6. Adding Up Inside a Loop
  9. 7. Looping Over a Map
  10. Code Examples
  11. Common Beginner Mistakes
  12. Practice Questions
  13. Practice Answers
  14. Key Takeaways

Lecture 020: for, for-in & forEach

Day8: Loops
Lecture020 of 057
Estimated video length14 min
TargetDart 3.12
LevelBeginner

Printing 100 receipts, adding up every mark in a list, checking each item in a cart: nobody writes the same line 100 times. A loop repeats a block of code for you. This lecture covers the three ways Dart loops over a range or a collection.

Contents

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


Prerequisites

Lectures 011 (lists), 014 (maps) and 015–016 (operators and if).


Learning Objectives

  • Write a counting for loop and read its three parts
  • Use ++, --, += and -=
  • Loop over a list by index and with for-in
  • Use forEach on a list
  • Add things up and count things inside a loop
  • Loop over a map's entries

1. The for Loop

dart
for (start; condition; step) {
  // repeated while condition is true
}
dart
for (var i = 1; i <= 5; i++) {
  print('Count: $i');
}

Output

code
Count: 1
Count: 2
Count: 3
Count: 4
Count: 5
  1. Start: var i = 1 runs once, before anything else.
  2. Condition: i <= 5 is checked before every round; when it's false, the loop ends.
  3. Step: i++ runs after every round.

2. Shortcut Operators

WriteMeans
i++i = i + 1
i--i = i - 1
i += 3i = i + 3
i -= 3i = i - 3
dart
for (var i = 10; i > 0; i -= 3) {
  print(i);   // 10, 7, 4, 1
}

3. Looping Over a List by Index

Indexes run from 0 to length - 1, so the condition is i < list.length:

dart
var fruits = ['apple', 'banana', 'mango'];
for (var i = 0; i < fruits.length; i++) {
  print('$i: ${fruits[i]}');
}

Output

code
0: apple
1: banana
2: mango

4. for-in: Each Item, No Index

When you don't need the position, for-in is simpler:

dart
for (var fruit in fruits) {
  print('I like $fruit');
}

5. forEach

Lists also have a forEach method that runs a small function for each item. (Functions are explained on Days 10 and 14; read it as "for each fruit, do this".)

dart
fruits.forEach((fruit) {
  print('forEach: $fruit');
});

for-in is usually preferred in your own code, but you'll see forEach often.

LoopUse when…
for (var i = 0; ...)you need the index, or a range of numbers
for (var x in list)you need each item
list.forEach((x) { ... })same as for-in, in function style

6. Adding Up Inside a Loop

Start a variable before the loop and update it on every round:

dart
var marks = [80, 65, 90, 72];
var total = 0;
for (var m in marks) {
  total += m;
}
print('Total: $total, average: ${total / marks.length}');
// Total: 307, average: 76.75

7. Looping Over a Map

dart
var ages = {'Ali': 20, 'Sara': 19};
for (var entry in ages.entries) {
  print('${entry.key} is ${entry.value}');
}
// Ali is 20
// Sara is 19

ages.keys and ages.values work in a for-in too.


Code Examples

Example 1: A Receipt and a Times Table

dart
void main() {
  var items = ['Rice', 'Oil', 'Sugar', 'Tea'];
  var prices = [320, 650, 180, 900];
  var total = 0;

  print('--- Receipt ---');
  for (var i = 0; i < items.length; i++) {
    print('${i + 1}. ${items[i]}: Rs ${prices[i]}');
    total += prices[i];
  }
  print('Total: Rs $total');

  var expensive = 0;
  for (var p in prices) {
    if (p > 500) {
      expensive++;
    }
  }
  print('Items over Rs 500: $expensive');

  print('--- 7 times table ---');
  for (var n = 1; n <= 5; n++) {
    print('7 x $n = ${7 * n}');
  }
}

Output

code
--- Receipt ---
1. Rice: Rs 320
2. Oil: Rs 650
3. Sugar: Rs 180
4. Tea: Rs 900
Total: Rs 2050
Items over Rs 500: 2
--- 7 times table ---
7 x 1 = 7
7 x 2 = 14
7 x 3 = 21
7 x 4 = 28
7 x 5 = 35

The receipt needs the index (to line items[i] up with prices[i] and number the lines), so it uses a counting loop. Counting expensive items only needs each price, so it uses for-in.


Common Beginner Mistakes

1. <= instead of < with length

dart
for (var i = 0; i <= fruits.length; i++) {
  print(fruits[i]);
}
code
apple
banana
mango
Unhandled exception:
RangeError (length): Invalid value: Not in inclusive range 0..2: 3

The last index is length - 1. Use i < fruits.length.

2. Changing the loop variable in for-in doesn't change the list

dart
var nums = [1, 2, 3];
for (var n in nums) {
  n = n * 2;
}
print(nums);   // [1, 2, 3]

n is a copy of each item. To change the list, use an index: nums[i] = nums[i] * 2;.

3. Adding to a list while looping over it

dart
for (var n in nums) {
  if (n == 2) nums.add(4);
}
code
Unhandled exception:
Concurrent modification during iteration: Instance(length:4) of '_GrowableList'.

Collect the new items in a separate list and add them after the loop.

4. Starting the total inside the loop: for (...) { var total = 0; total += m; } resets it every round. Declare it before the loop.


Practice Questions

  1. How many times does for (var i = 0; i < 4; i++) run?
  2. What does for (var i = 2; i <= 10; i += 4) print(i); print?
  3. Write a for-in loop that prints every name in names in capitals.
  4. Write a loop that adds up [5, 10, 15].
  5. Why does i <= list.length crash?
  6. Which loop do you need to print 1. Rice, 2. Oil (numbered lines)?

Practice Answers

  1. 4 times (i = 0, 1, 2, 3).
  2. 2, 6, 10.
  3. for (var name in names) { print(name.toUpperCase()); }
dart
var total = 0;
for (var n in [5, 10, 15]) {
  total += n;
}
print(total);   // 30
  1. On the last round i equals length, which is one past the last index.
  2. A counting for loop: you need the index for the numbers (i + 1).

Key Takeaways

  • for (start; condition; step) repeats while the condition is true.
  • i++, i--, +=, -= update counters.
  • Loop over a list with i < list.length, or for (var x in list) when you don't need the index.
  • forEach does the same as for-in, in function style.
  • Declare totals and counters before the loop.