CodeBlanks Logo Icon CodeBlanks

The for loop

Learn to write counted loops with for.

The for loop

To repeat a code block a fixed number of times you use a for loop. The form is for (init; condition; update) { ... }. The init runs once; the condition is checked before each iteration; the update runs after each iteration.

For example for (var i = 1; i <= 3; i++) { print(i); } prints 1, 2, 3. i++ increases i by one. When the condition becomes false the loop ends.

Init, condition, update

The for loop has three parts: init (var i = 1), condition (i <= 5) and update (i++). The init runs once before the loop; the condition is checked before each iteration; the update runs after each iteration.

The update is not always i++. With i += 2 you count by twos; with i-- you count backwards. When counting backwards adjust the condition: for (var i = 5; i >= 1; i--) { print(i); } counts from 5 down to 1.

Practice Count from 1 to 5

Build a for (var i = 1; i <= 5; i++) loop. In the body print each number with print(i);. The output must be 5 lines: 1, 2, 3, 4, 5 (one number per line).

Starter code

main.dart
// Count from 1 to 5 with a for loop and print each

Sample solution

main.dart
for (var i = 1; i <= 5; i++) {
  print(i);
}

Expected output

1
2
3
4
5

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 How many times does this loop run?

main.dart
for (var i = 1; i <= 3; i++) {
  print(i);
}
  • 3 times Correct answer
  • 1 time
  • Infinitely
  • 0 times

Explanation: The condition is true for i=1, 2, 3; 3 iterations run.

2 Complete the for header

Question
for (____) {
  print(i);
}
Answer
for (var i = 1; i <= 5; i++) {
  print(i);
}

Explanation: for (var i = 1; i <= 5; i++) has all three parts.

3 Match each part to its job

Term Meaning
var i = 1 Init
i <= 5 Condition
i++ Update
{ ... } Body

All lessons in Beginner