Write a program that prints the numbers from 1 to 100. But for multiples of three print “Fizz” instead of the number and for the multiples of five print “Buzz”. For numbers which are multiples of both three and five print “FizzBuzz”.

Tuesday, January 24, 2012

#7 - Decomposed Loop

It's hard to take a look at a programming solution to FizzBuzz from an absolute ground state.  There are at least three concepts that need to be working at a basic level for a solution to be sensible: repetition, decisions, and calculation.  To analyze any of those three aspects you need two of them standing fairly unchanged while one of them is decomposed.

First I shall decompose the nature of the solution by changing the basic ways a loop can be constructed.    Given the prevalence of C and Java as arguably the most popular language in programming language for over a quarter century the three expression for loop is something that any professional or accomplished amateur should understand instinctively.  But what does that three expression loop look like when decomposed in a semantically similar fashion??


public class FizzBuzz07 {
  public static void main(String[] args) {
    int i = 1;
    while (i <= 100) {
      if ((i % 3 == 0) && (i % 5 == 0)) {
        System.out.println("FizzBuzz");
      } else if (i % 5 == 0) {
        System.out.println("Buzz");
      } else if (i % 3 == 0) {
        System.out.println("Fizz");
      } else {
        System.out.println(i);
      }
      i++;
    }
  }
}

The three expression for loop actually has four parts.  The part that often gets ignored is the loop body, expressed by lines 5 through 13 and is not counted in the three expressions.  Since C and Java have zero based arrays, we could call this the zeroth expression.

The first expression sets initial values and variables and is seen in line 3.  Strictly speaking this is not a proper decomposition since the scope of the variable in this decomposition could extend beyond the loop body, if there were expressions other than the loop.  The second expression is a test, and is found inside the while expression on line 4.  The last expression is found on line 14, executed after the content of the body.

As an aside, the last entry on Ceylon didn't feature a three expression loop because Ceylon doesn't support the syntax.  That was the position Groovy once took but later relented when it added the "classic for loop" in it's 1.5 release.  However, Ceylon and Groovy both have a while loop construct.  So by applying the FizzBuzz Hypothesis we can see that programmers don't need a nice neat for loop expression.  But it sure looks prettier with one.

No comments:

Post a Comment