Control Flow
For Loop
Accumulating a Total
A C-style for (init; cond; step) runs the body until the condition is false. += updates accumulator state.
Program
Play the program to sum the numbers 1 through 3.
for_loop.dart
Replay: real traced execution (multi-file project)
void main() {
var total = 0;
for (var i = 1; i <= 3; i++) {
total += i;
}
print(total);
}
total ← 0
1void main() {2 var total = 0;3 for (var i = 1; i <= 3; i++) {values this step0totali ← 1
2var total = 0;3for (var i = 1; i <= 3; i++) {4 total += i;values this step1itotal ← 1
3for (var i = 1; i <= 3; i++) {4 total += i;5}values this step0 → 1total1ii ← 2
2var total = 0;3for (var i = 1; i <= 3; i++) {4 total += i;values this step2itotal ← 3
3for (var i = 1; i <= 3; i++) {4 total += i;5}values this step1 → 3total2ii ← 3
2var total = 0;3for (var i = 1; i <= 3; i++) {4 total += i;values this step3itotal ← 6
3for (var i = 1; i <= 3; i++) {4 total += i;5}values this step3 → 6total3iprint(total);
5 }6 print(total);7}output6values this step6total
Add One Through Three
totalstarts at0.- The loop runs with
i = 1, then2, then3. - Each pass adds
iintototal. - The program prints
6. |i| Running total | | --- | --- | |1|1| |2|3| |3|6|
for
`for (init; cond; step)` is the classic counted loop.
++ and +=
`i++` post-increments; `total += i` adds in place.
accumulator
`total` carries state across iterations.
Exercise: for_loop.dart
Use a for loop to add 1, 2, and 3 into total and print 6