DMarlon Studio

Lesson 8 · 8 of 20

for, while and do-while · Dart

Repeat code in Dart with for, while and do-while loops, and control each turn with break and continue: a times table, savings and a countdown.

Dart · for, while and do-while in DMarlon Studio: the example's code and its output in the terminal

A `for` loop has three parts in brackets, separated by semicolons: the start (int i = 1), the condition to keep going (i <= 5) and the step after each turn (i++). That way it goes through the numbers 1 to 5 and prints the 7 times table.

`while` repeats as long as its condition is true, without knowing in advance how many turns it will take. The savings grow by 10% a year (savings *= 1.10) until they pass 150 euros, and years counts the turns: it takes 5 years.

`do-while` checks the condition at the end, so the block runs at least once. The countdown prints 3, 2 and 1, and stops when countdown reaches 0. Note the semicolon after while (...).

Inside a loop, `continue` jumps straight to the next turn and `break` leaves the loop altogether. The last for goes from 1 to 20, but skips even numbers with continue and stops as soon as n goes past 11 with break.

Code · main.dart

void main() {  // for: a start, a condition and a step.  for (int i = 1; i <= 5; i++) {    print('7 x $i = ${7 * i}');  }  // while repeats as long as the condition is true.  double savings = 100;  int years = 0;  while (savings < 150) {    savings *= 1.10; // 10% interest each year    years++;  }  print('$years years to reach ${savings.toStringAsFixed(2)} euros');  // do-while checks at the end, so it runs at least once.  int countdown = 3;  do {    print('Countdown: $countdown');    countdown--;  } while (countdown > 0);  // continue jumps to the next turn; break leaves the loop.  String odds = '';  for (int n = 1; n <= 20; n++) {    if (n % 2 == 0) continue;    if (n > 11) break;    odds += '$n ';  }  print('Odd numbers up to 11: $odds');}

Output · dart run main.dart

7 x 1 = 7
7 x 2 = 14
7 x 3 = 21
7 x 4 = 28
7 x 5 = 35
5 years to reach 161.05 euros
Countdown: 3
Countdown: 2
Countdown: 1
Odd numbers up to 11: 1 3 5 7 9 11

Key points

  • for (start; condition; step) when you know how many turns.
  • while (condition) for as long as something holds.
  • do { } while (condition); runs at least once.
  • continue moves to the next turn; break leaves.

Exercise

With a while, work out how many times you must fold a sheet of paper (each fold doubles its thickness; start at 0.1 mm) until it is thicker than one metre.