Skip to content
Tutorials Center
My learning

Topics

Lesson 13 of 61 ยท Control Flow

Loops: for, while and do-while

Learn Dart loops: the classic for loop, for-in over collections, while and do-while, break, continue and labels, with runnable TypeScript stand-ins.

A loop repeats a block of code. Dart gives you the loops you know from most languages: a counting for, a for-in that walks over a collection, while, and do-while. Together with break and continue they cover almost every repetition you will write.

If you have not yet seen how Dart decides between branches, read if, else and conditional expressions first. Here we focus on repetition. The Dart snippets are read-only; the TypeScript stand-ins next to them run on the site and use the same shapes.

The classic for loop

A for loop has three parts in its header: an initializer, a condition and an update step.

DART
void main() {
  for (var i = 1; i <= 3; i++) {
    print('Round $i');
  }
}
TEXT
Round 1
Round 2
Round 3

The initializer var i = 1 runs once. The condition i <= 3 is checked before every round, and i++ runs after each round. When the condition becomes false, the loop ends and the program continues after it. The variable i only exists inside the loop.

You can count down or skip numbers by changing the update step:

DART
void main() {
  for (var i = 10; i > 0; i -= 3) {
    print(i); // 10, 7, 4, 1
  }
}

Dart has no range syntax such as 1..5 for loops, so the counting for is the tool when you need an index.

TypeScript Counting with for (stand-in)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

Each round gets its own variable

One Dart detail is worth knowing: every iteration of a for loop gets a fresh copy of the loop variable. Closures created inside the loop therefore remember the value from their own round.

DART
void main() {
  final printers = <void Function()>[];
  for (var i = 0; i < 3; i++) {
    printers.add(() => print(i));
  }
  for (final p in printers) {
    p();
  }
}
TEXT
0
1
2

In languages where all rounds share one variable, this would print 3 three times. Dart does what most people expect.

for-in: walking over a collection

When you do not need the index, for-in is shorter and safer. It works with any Iterable: lists, sets, the keys of a map, a string's characters when you ask for them, and so on.

DART
void main() {
  final fruits = ['apple', 'banana', 'cherry'];
  for (final fruit in fruits) {
    print(fruit.toUpperCase());
  }
}

Use final for the loop variable when you do not reassign it. Dart creates a new fruit for every element.

A Map is not an Iterable itself, so you pick which view to walk: keys, values or entries.

DART
void main() {
  final stock = {'apple': 4, 'pear': 0, 'plum': 9};
  for (final entry in stock.entries) {
    print('${entry.key}: ${entry.value}');
  }
}

With patterns (covered in Patterns and destructuring) you can unpack each entry directly in the header: for (final MapEntry(key: name, value: count) in stock.entries).

If you need both the position and the element, you can loop over the indexes, or use asMap() or the indexed property on iterables:

DART
void main() {
  final names = ['Ada', 'Grace', 'Linus'];
  for (final (index, name) in names.indexed) {
    print('${index + 1}. $name');
  }
}
TEXT
1. Ada
2. Grace
3. Linus
TypeScript Walking over lists and maps (stand-in)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

Do not add or remove elements of a list while you are looping over it with for-in. Dart throws a ConcurrentModificationError. Build a new list, or collect the changes and apply them after the loop. The Lists lesson shows removeWhere, which does this safely in one call.

while and do-while

A while loop checks its condition first and runs the body as long as the condition is true. Use it when you do not know in advance how many rounds you need.

DART
void main() {
  var n = 27;
  var steps = 0;
  while (n != 1) {
    n = n.isEven ? n ~/ 2 : 3 * n + 1;
    steps++;
  }
  print('Reached 1 after $steps steps.');
}

The operator ~/ is integer division, covered in Numbers. If the condition is false at the start, the body never runs.

A do-while loop runs the body first and checks the condition afterwards, so the body always runs at least once. That is useful for "ask, then validate" patterns:

DART
import 'dart:io';

void main() {
  String? answer;
  do {
    stdout.write('Type yes to continue: ');
    answer = stdin.readLineSync();
  } while (answer != 'yes');
  print('Continuing.');
}

Note the semicolon after the closing while (...). It is required for do-while, and only there.

flowchart TD
    S["Start"] --> W{"while: condition true?"}
    W -->|"yes"| B1["Run the body"]
    B1 --> W
    W -->|"no"| E["After the loop"]
    S2["do-while: run the body first"] --> B2["Run the body"]
    B2 --> C{"Condition true?"}
    C -->|"yes"| B2
    C -->|"no"| E2["After the loop"]

A while loop tests before each round; a do-while loop tests after it.

TypeScript while and do-while (stand-in)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

break and continue

break leaves the nearest loop immediately. continue skips the rest of the current round and jumps to the next one.

DART
void main() {
  final numbers = [3, 8, -1, 5, 0, 7];
  var sum = 0;
  for (final n in numbers) {
    if (n < 0) continue; // ignore negatives
    if (n == 0) break;   // stop at the first zero
    sum += n;
  }
  print(sum); // 3 + 8 + 5 = 16
}

In a for loop, continue still runs the update step (i++) before the next check. In a while loop there is no update step, so make sure your own counter changes before the continue, or you will loop forever.

Labels for nested loops

A plain break only leaves the innermost loop. To leave an outer loop, put a label before it and name it:

DART
void main() {
  outer:
  for (var row = 1; row <= 3; row++) {
    for (var col = 1; col <= 3; col++) {
      if (row * col == 4) {
        print('Found $row x $col');
        break outer;
      }
      print('$row x $col = ${row * col}');
    }
  }
}
TEXT
1 x 1 = 1
1 x 2 = 2
1 x 3 = 3
2 x 1 = 2
Found 2 x 2

continue outer; works too: it abandons the inner loop and starts the next round of the outer one. Labels are rarely needed. If you find yourself using one often, consider moving the nested loops into a function and using return instead.

TypeScript break, continue and labels (stand-in)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

Dart has no goto. Labels only work together with break and continue on a loop (or break on a switch), so you can leave or skip an outer loop but never jump to an arbitrary line.

forEach and collection for

Iterables also have a forEach method that takes a function:

DART
void main() {
  [1, 2, 3].forEach(print);
}

It looks neat for a single call, but you cannot use break, continue or await inside the callback in a useful way. The Dart style guide recommends a plain for-in loop when you pass a function literal. Reserve forEach for tear-offs such as print, which you will meet in First-class functions.

Dart also has a collection for, a loop that builds a list, set or map from inside the literal:

DART
void main() {
  final squares = [for (var i = 1; i <= 5; i++) i * i];
  print(squares); // [1, 4, 9, 16, 25]
}

It can be combined with a collection if, which you saw in the conditionals lesson. Use it when the loop's only job is to create a collection.

Choosing a loop

  • Need the index or a custom step? Use the counting for.
  • Visiting every element? Use for-in.
  • Repeating until something happens? Use while.
  • Must run at least once? Use do-while.
  • Building a collection? Consider a collection for or the map and where methods from Iterables.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What is the difference between while and do-while?

    A do-while loop runs the body first and tests the condition afterwards, so the body executes once even if the condition is false from the start.
  2. 2. Which loop is the best fit for visiting every element of a list when you do not need the index?

    for-in is shorter and avoids off-by-one mistakes. It works with any Iterable.
  3. 3. What happens if you remove items from a list inside a for-in loop over that same list?

    Changing the length of a collection while iterating over it is not allowed. Build a new list or use a method such as removeWhere.
  4. 4. How do you leave an outer loop from inside an inner loop?

    Put a label such as outer: before the outer loop, then use break outer; or continue outer; in the inner one.

Summary

  • for (init; condition; update) is the counting loop; each round gets its own copy of the loop variable.
  • for-in walks any Iterable. For a Map, loop over keys, values or entries.
  • while tests first, do-while tests last and always runs once (and needs a closing semicolon).
  • break leaves a loop, continue skips to the next round, and labels let you target an outer loop.
  • Do not change a collection's length while iterating over it.
  • Prefer for-in over forEach with a function literal.

Next: switch statements and expressions.