๐ŸŽ“ A1Learner
๐Ÿ”
0 of 40 lessons completed

Dart For Loop

A for loop repeats a block a counted number of times. The loop header holds the start, the condition, and the step.

Counting from one to three

The counter starts at 1 and grows by one each run. The loop stops after the counter passes 3.

void main() {
  for (var i = 1; i <= 3; i++) {
    print(i);
  }
}

Counting down

The counter starts at 3 and drops by one each run. The loop stops after the counter passes 1.

void main() {
  for (var i = 3; i >= 1; i--) {
    print(i);
  }
}

Steps of two

The step adds two after each run. Only the even numbers from 2 to 8 reach the screen.

void main() {
  for (var i = 2; i <= 8; i += 2) {
    print(i);
  }
}

Adding up in a loop

Each run adds the counter to total. The final total holds the sum of 1 to 4.

void main() {
  var total = 0;
  for (var i = 1; i <= 4; i++) {
    total += i;
  }
  print(total);
}

Example

void main() {
  for (var i = 1; i <= 5; i++) {
    print('Round $i');
  }
}

Key points

  • Use a for loop to repeat a block a known number of times.
  • The start sets the counter before the first run.
  • The condition is tested before each run.
  • The step changes the counter after each run.
  • The three header parts sit apart with semicolons.
  • Use i++ to grow the counter by one after each run.

In this example, the counter starts at 1. Each run prints one line with the current counter value. The step grows the counter by one after each run. The condition fails at 6, so the loop stops after five lines.

Try it Yourself

Edit the code, then press Run.

Running is simulated ยท DartPad

Exercise

What does the step part of a for loop do?