FizzBuzz
In terms of elegance and maintainabillity, I like this solution best, even though it makes the least use of language features:
for (int i = 0; i < 100; i++) {
boolean fizzOrBuzz = false;
if (i % 3) {
print("fizz"); fizzOrBuzz = true;
}
if (i % 5) {
print("buzz"); fizzOrBuzz = true;
}
if (!fizzOrBuzz) {
print(i);
}
}
@Astaedus said:
Is there any situation, *any* situation, where using the foreach loop results in a better software product than not using it? No, because a good compiler will probably produce the same result for both loops.
Sure there is. Java:
public void doStuffForAll(List things) {
for (int i = 0; i < things.size(); i++) {
doStuff(things.get(i));
}
}
this works like a charm - as long as your list allows random access. But as soon as someone decides to pass a linked list, your running time explodes. Unfortunately you can't easily detect that if you want to keep things generic. The equivalent for-each version doesn't have this problem - because the list (and not your code) does the actual iterating, each implementation can choose the most efficient way.
(I think I brought the same example in an earlier thread for a different problem. Apologies if I start repeating myself.)