A C-style for (init; cond; step) runs the body until the condition is false. += updates accumulator state.

Program

Play the program to sum the numbers 1 through 3.

for_loop.dart
Replay: real traced execution (multi-file project)
void main() {
  var total = 0;
  for (var i = 1; i <= 3; i++) {
    total += i;
  }
  print(total);
}
  1. total ← 0

    1void main() {2  var total = 0;3  for (var i = 1; i <= 3; i++) {
    values this step0total
  2. i ← 1

    2var total = 0;3for (var i = 1; i <= 3; i++) {4  total += i;
    values this step1i
  3. total ← 1

    3for (var i = 1; i <= 3; i++) {4  total += i;5}
    values this step0 1total1i
  4. i ← 2

    2var total = 0;3for (var i = 1; i <= 3; i++) {4  total += i;
    values this step2i
  5. total ← 3

    3for (var i = 1; i <= 3; i++) {4  total += i;5}
    values this step1 3total2i
  6. i ← 3

    2var total = 0;3for (var i = 1; i <= 3; i++) {4  total += i;
    values this step3i
  7. total ← 6

    3for (var i = 1; i <= 3; i++) {4  total += i;5}
    values this step3 6total3i
  8. print(total);

    5  }6  print(total);7}
    output6
    values this step6total

Add One Through Three

  1. total starts at 0.
  2. The loop runs with i = 1, then 2, then 3.
  3. Each pass adds i into total.
  4. The program prints 6. | i | Running total | | --- | --- | | 1 | 1 | | 2 | 3 | | 3 | 6 |
for `for (init; cond; step)` is the classic counted loop.
++ and += `i++` post-increments; `total += i` adds in place.
accumulator `total` carries state across iterations.

Exercise: for_loop.dart

Use a for loop to add 1, 2, and 3 into total and print 6