Async and Practical
FizzBuzz Rule Order
FizzBuzz is the classic test of else if ordering: % 15 has to be checked first, otherwise 15 would match % 3 and get labeled Fizz. The loop appends one label per value and a final join builds the deterministic summary.
Program
Play the program to label four numbers with FizzBuzz rules.
fizzbuzz.dart
Replay: real traced execution (multi-file project)
void main() {
var values = [15, 3, 5, 16];
var labels = <String>[];
for (var n in values) {
if (n % 15 == 0) {
labels.add('FizzBuzz');
} else if (n % 3 == 0) {
labels.add('Fizz');
} else if (n % 5 == 0) {
labels.add('Buzz');
} else {
labels.add('$n');
}
}
print(labels.join(','));
}
values ← [15, 3, 5, 16]
1void main() {2 var values = [15, 3, 5, 16];3 var labels = <String>[];values this step[15, 3, 5, 16]valueslabels ← []
2var values = [15, 3, 5, 16];3var labels = <String>[];4for (var n in values) {values this step[]labelsrules ← %15, %3, %5, else
3var labels = <String>[];4for (var n in values) {5 if (n % 15 == 0) {values this step%15, %3, %5, elserules[15, 3, 5, 16]valueslabel ← FizzBuzz
5if (n % 15 == 0) {6 labels.add('FizzBuzz');7} else if (n % 3 == 0) {values this stepFizzBuzzlabel15nlabel ← Fizz
7} else if (n % 3 == 0) {8 labels.add('Fizz');9} else if (n % 5 == 0) {values this stepFizzlabel3nlabel ← Buzz
9} else if (n % 5 == 0) {10 labels.add('Buzz');11} else {values this stepBuzzlabel5nlabel ← 16
11} else {12 labels.add('$n');13}values this step16label16nlabels ← [FizzBuzz, Fizz, Buzz, 16]
13 }14}15print(labels.join(','));values this step[FizzBuzz, Fizz, Buzz, 16]labelsprint(labels.join(','));
14 }15 print(labels.join(','));16}outputFizzBuzz,Fizz,Buzz,16values this step[FizzBuzz, Fizz, Buzz, 16]labels
rule order
`% 15` is checked first; otherwise `15` would match `% 3` and stop as `Fizz`.
else if chain
Only one arm runs per iteration; once a match wins, the rest are skipped.
collect then join
Appending to `labels` and joining once at the end keeps the final string deterministic.