input is n
| 3 divides n | 5 divides n | result |
|—————————————|—————————————|————————————|
| Yes | Yes | “FizzBuzz” |
| Yes | No | “Fizz” |
| No | Yes | “Buzz” |
| No | No | n.toString |
print result
The key points are:1. The logic is declarative: the order of the rows in the table doesn’t matter.
2. It tests for divisibility in words rather than a potentially confusing idiom (how does % behave for negative numbers? Is it defined for floats in this language?)
3. The structure allows you (or a compiler) to check that no case is missed.
4. It should be easier to convince oneself that modifications to the code do what they are supposed to.
The funny thing is that looking things up in tables is much more common in excel.
Not printing in the middle, return a string and afterwards print it.
Each step adds to the string, and if it's still empty by the end you just put the number in.
The next stages are often to add another number, then something more complex (if it's a prime number). As you do this, the concatenation version grows slowly while the first approach explodes in combinations.