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
Replay: real traced execution (multi-file project)
void main() {
  var n = 1;
  var sum = 0;
  while (n <= 3) {
    sum = sum + n;
    n = n + 1;
  }
  print('sum=$sum');
}
  1. n ← 1

    1void main() {2  var n = 1;3  var sum = 0;
    values this step1n
  2. sum ← 0

    2var n = 1;3var sum = 0;4while (n <= 3) {
    values this step0sum
  3. check ← 1 <= 3 (true)

    3var sum = 0;4while (n <= 3) {5  sum = sum + n;
    values this step1 <= 3 (true)check1n
  4. sum ← 1

    4while (n <= 3) {5  sum = sum + n;6  n = n + 1;
    values this step0 1sum1n
  5. n ← 2

    5  sum = sum + n;6  n = n + 1;7}
    values this step1 2n
  6. check ← 2 <= 3 (true)

    3var sum = 0;4while (n <= 3) {5  sum = sum + n;
    values this step2 <= 3 (true)check2n
  7. sum ← 3

    4while (n <= 3) {5  sum = sum + n;6  n = n + 1;
    values this step1 3sum2n
  8. n ← 3

    5  sum = sum + n;6  n = n + 1;7}
    values this step2 3n
  9. check ← 3 <= 3 (true)

    3var sum = 0;4while (n <= 3) {5  sum = sum + n;
    values this step3 <= 3 (true)check3n
  10. sum ← 6

    4while (n <= 3) {5  sum = sum + n;6  n = n + 1;
    values this step3 6sum3n
  11. n ← 4

    5  sum = sum + n;6  n = n + 1;7}
    values this step3 4n
  12. check ← 4 <= 3 (false)

    3var sum = 0;4while (n <= 3) {5  sum = sum + n;
    values this step4 <= 3 (false)check4n
  13. print('sum=$sum');

    7  }8  print('sum=$sum');9}
    outputsum=6
    values this step6sum

Add While N Is Small

  1. n starts at 1.
  2. sum starts at 0.
  3. The loop runs while n <= 3.
  4. Each pass adds n, then increases n.
  5. The program prints sum=6. | n before pass | Running sum | | --- | --- | | 1 | 1 | | 2 | 3 | | 3 | 6 |
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`.

Exercise: while_loop.dart

Use a while loop to add n from 1 through 3 and print sum=6