A while loop checks its condition first. If the condition is true, the body runs and the condition is re-checked. When the condition becomes false, the loop exits and control falls through to the next statement. The body must change the variables the condition reads, otherwise the loop never ends.

Program

Play the program to count n from 1 to 3, accumulate sum, and watch the condition flip to false on the fourth check.

while_loop.dart
void main() {
  var n = 1;
  var sum = 0;
  while (n <= 3) {
    sum = sum + n;
    n = n + 1;
  }
  print('sum=$sum');
}
while `while (cond) { body }` re-evaluates `cond` before each iteration and runs `body` while `cond` is `true`.
body advances state `sum = sum + n` and `n = n + 1` change the variables the condition reads. Without that update, the loop would run forever.
exit on false When `n` becomes `4`, the check `4 <= 3` is `false`, the loop ends, and control moves on to `print`.