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”.

Thursday, January 26, 2012

#8 - Do while I'm doing

Now that we have examined the while loop in C style languages, it's time to consider the while loops delinquent little brother: the do-while loop.  This is a fairly unique control structure that requires a keyword both at the beginning and the end of it's structure.  Kind of like the try-catch clause, except that you only try once but you do the loop at least once, and then consider whether you continue or not.  This does have one slight advantage in readability:  if you decide not to continue you are right at the code block you will evaluate next.

public class FizzBuzz08 { 
  public static void main(String[] args) { 
    int i = 1; 
    do {
      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); 
      } 
    } while (i++ < 100); 
  } 
}

This code isn't dramatically different from the previous entry where the while loop was considered.  The body is still on lines 5 through 13, and the first expression is on line 3.

The differences come in the second and third expression.  I combined both of them on line 14 for stylistic reasons.  First, the order of the expressions would not have been maintained since the increment would occur before the test.  I then moved the post increment into the while test expression so we can use the less than operator instead of the less than and equal.  One less keystroke.  Although since I am programming in Java I don't know why I worry about minimizing keystrokes.

This loop is not a direct decomposition of a for loop.  The loop body will always be evaluated once regardless of the truth of the expression.  So this is not a good case of the always evaluate logic.  So if a do-while smells like a simple while, typical developers can code it correctly.  However whether they can use the always evaluate aspect correctly is up for debate.

No comments:

Post a Comment