Control Flow
While Loop
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');
}
n ← 1
1void main() {2 var n = 1;3 var sum = 0;values this step1nsum ← 0
2var n = 1;3var sum = 0;4while (n <= 3) {values this step0sumcheck ← 1 <= 3 (true)
3var sum = 0;4while (n <= 3) {5 sum = sum + n;values this step1 <= 3 (true)check1nsum ← 1
4while (n <= 3) {5 sum = sum + n;6 n = n + 1;values this step0 → 1sum1nn ← 2
5 sum = sum + n;6 n = n + 1;7}values this step1 → 2ncheck ← 2 <= 3 (true)
3var sum = 0;4while (n <= 3) {5 sum = sum + n;values this step2 <= 3 (true)check2nsum ← 3
4while (n <= 3) {5 sum = sum + n;6 n = n + 1;values this step1 → 3sum2nn ← 3
5 sum = sum + n;6 n = n + 1;7}values this step2 → 3ncheck ← 3 <= 3 (true)
3var sum = 0;4while (n <= 3) {5 sum = sum + n;values this step3 <= 3 (true)check3nsum ← 6
4while (n <= 3) {5 sum = sum + n;6 n = n + 1;values this step3 → 6sum3nn ← 4
5 sum = sum + n;6 n = n + 1;7}values this step3 → 4ncheck ← 4 <= 3 (false)
3var sum = 0;4while (n <= 3) {5 sum = sum + n;values this step4 <= 3 (false)check4nprint('sum=$sum');
7 }8 print('sum=$sum');9}outputsum=6values this step6sum
Add While N Is Small
nstarts at1.sumstarts at0.- The loop runs while
n <= 3. - Each pass adds
n, then increasesn. - The program prints
sum=6. |nbefore 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