Sunday, August 30, 2009

FizzBuzz

On the first day of ICS 413, Dr. Johnson instructed us to implement the FizzBuzz program in Java. My first thought upon hearing the assignment was "I've forgotten a lot of Java knowledge!" Over the summer I had been doing programming in Maple, a technical computing software, during a mathematics research program; moreover, the last time I did any programming in Java was almost a year ago, last fall. So although I could immediately visualize the algorithm that I wanted to implement, it took a little bit of thinking to remember Java's syntax.

In the time given in class to write the program by hand (around five minutes, I think), I was able to complete the program with what I believe would have amounted to a few syntactical errors. Later, when I used the Eclipse IDE to write the program, I had no problems and was able to implement the program within a few minutes.



Program description:
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".



My program:

/*
*  This program prints out the number from 1 to 100, inclusive, with one
*  number on each line. However, if the number is divisible by three, it
*  instead prints the word "Fizz", if the number is divisible by five, it
*  instead prints the word "Buzz", and if the number is divisible by both
*  three and five, it prints the word "FizzBuzz".
*/
public class FizzBuzz {
  
public static void main(String[] args){
      
      
// Loop through the number from 1 to 100
      
for(int i=1; i<=100;i++){
          
if(i%15==0){
              
/*
                *  If the number is divisible by both 3 and 5 (i.e.
                *  divisible by 15), print out "FizzBuzz".
                */
              
System.out.println("FizzBuzz");
          
}
          
else if(i%3==0){
              
// If the number is divisible by 3, print out "Fizz".
              
System.out.println("Fizz");
          
}
          
else if(i%5==0){
              
// If the number is divisible by 5, print out "Buzz".
              
System.out.println("Buzz");
          
}
          
else{
              
/*
                *  If the number is not divisible by 3 or 5 (or both),
                *  then print out the number.
                */
              
System.out.println(i);
          
}
       }
   }
}




This experience has shown me that even the simplest of programs can be good exercises to get used to programming in a language that one has learned in the past but may have not used recently. Also, the experience has shown me not to dismiss programming assignments as trivial or to underestimate an assignment.

No comments:

Post a Comment