Sunday, August 30, 2009

Fizz Buzz Program

It was pretty interesting that the very first thing we did in class, after learning everybody's name and expectations from this class, was to write a comparable program that prospective programmers might expect in a job interview.
The program is called FizzBuzz, which prints the numbers from 1 to 100 and substitutes "Fizz" for numbers divisible by 3, "Buzz" by 5 and "FizzBuzz" by 3 & 5.

I did manage to write the program correctly but it was a little different from the one we did as a class. For my "FizzBuzz" line I have:
if (i % 15 == 0) {
  System.out.println
("FizzBuzz");
}


And as a collective class effort we came up with:
if (i % 15 == 0) {
  System.out.println
("FizzBuzz");
}


It was interesting what everybody came up with considering there are different approach for solving the problem. I realized that our class' approach was better in terms of style and efficiency, my approach had two comparisons whereas the class' had only one.
So when I wrote the same program in Eclipse, I used our class' solution.

Here is my FizzBuzz Code:
/*
* Prints out the number from 1 to 100 but
* substitute Fizz for all multiple of 3,
* Buzz for 5 and FizzBuzz for 3 and 5.
*/
public class FizzBuzz {
  
public Static void main(String[] args) {
    
for (int i = 1; i <= 100; i++) {
      
if (i % 15 == 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);
      
}
    }
  }
}


As for Eclipse, I have been using it as my IDE since ICS111 so I learned a few shortcuts and it took me no less than 4 min to write and run the program with no problems.

0 comments:

Post a Comment