On this page14 sections
Lecture 020: for, for-in & forEach
| Day | 8: Loops |
| Lecture | 020 of 057 |
| Estimated video length | 14 min |
| Target | Dart 3.12 |
| Level | Beginner |
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
forloop and read its three parts - Use
++,--,+=and-= - Loop over a list by index and with
for-in - Use
forEachon a list - Add things up and count things inside a loop
- Loop over a map's entries
1. The for Loop
for (start; condition; step) {
// repeated while condition is true
}for (var i = 1; i <= 5; i++) {
print('Count: $i');
}Output
Count: 1
Count: 2
Count: 3
Count: 4
Count: 5- Start:
var i = 1runs once, before anything else. - Condition:
i <= 5is checked before every round; when it's false, the loop ends. - Step:
i++runs after every round.
2. Shortcut Operators
| Write | Means |
|---|---|
i++ | i = i + 1 |
i-- | i = i - 1 |
i += 3 | i = i + 3 |
i -= 3 | i = i - 3 |
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:
var fruits = ['apple', 'banana', 'mango'];
for (var i = 0; i < fruits.length; i++) {
print('$i: ${fruits[i]}');
}Output
0: apple
1: banana
2: mango4. for-in: Each Item, No Index
When you don't need the position, for-in is simpler:
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".)
fruits.forEach((fruit) {
print('forEach: $fruit');
});for-in is usually preferred in your own code, but you'll see forEach often.
| Loop | Use 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:
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.757. Looping Over a Map
var ages = {'Ali': 20, 'Sara': 19};
for (var entry in ages.entries) {
print('${entry.key} is ${entry.value}');
}
// Ali is 20
// Sara is 19ages.keys and ages.values work in a for-in too.
Code Examples
Example 1: A Receipt and a Times Table
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
--- 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 = 35The 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
for (var i = 0; i <= fruits.length; i++) {
print(fruits[i]);
}apple
banana
mango
Unhandled exception:
RangeError (length): Invalid value: Not in inclusive range 0..2: 3The last index is length - 1. Use i < fruits.length.
2. Changing the loop variable in for-in doesn't change the list
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
for (var n in nums) {
if (n == 2) nums.add(4);
}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
- How many times does
for (var i = 0; i < 4; i++)run? - What does
for (var i = 2; i <= 10; i += 4) print(i);print? - Write a
for-inloop that prints every name innamesin capitals. - Write a loop that adds up
[5, 10, 15]. - Why does
i <= list.lengthcrash? - Which loop do you need to print
1. Rice,2. Oil(numbered lines)?
Practice Answers
- 4 times (
i= 0, 1, 2, 3). 2,6,10.for (var name in names) { print(name.toUpperCase()); }
var total = 0;
for (var n in [5, 10, 15]) {
total += n;
}
print(total); // 30- On the last round
iequalslength, which is one past the last index. - A counting
forloop: 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, orfor (var x in list)when you don't need the index. forEachdoes the same asfor-in, in function style.- Declare totals and counters before the loop.