I ran across “FizzBuzz” today, which is an interview problem that is given at some employers for potential software developers. I was intrigued by the stated problem and I could not wait to get home to try and figure it out. Little did I know I would be finished in less than 5 minutes. Oh well, it was fun to think about during the day. Below is my code samples in Java:
Using a for loop:
/*Objective:
* Write a program that prints the numbers from 1 to 100.
But for multiples of three print "Fizz" instead of the number.
For the multiples of five print "Buzz".
For numbers which are multiples of both three and five print "FizzBuzz".
* */
public class ForFizzBuzz {
public static void main(String[] args) {
int i;
for (i = 1; i < 101; i++){
if (i % 3 == 0) {
System.out.print("Fizz");
}else if (i % 5 == 0) {
System.out.print("Buzz");
}else{
System.out.print(i);
}
System.out.println();
}
}
}
Using a while loop (with a twist):
/*Objective:
* Write a program that prints the numbers from 1 to 100.
But for multiples of three print "Fizz" instead of the number.
For the multiples of five print "Buzz".
For numbers which are multiples of both three and five print "FizzBuzz".
* */
public class WhileFizzBuzz {
public static void main(String[] args) {
int i = 0;
boolean visited = false;
while (i < 101) {
if (i % 3 == 0) {
System.out.print("Fizz");
visited=true;
}
if (i % 5 == 0) {
System.out.print("Buzz");
visited=true;
}
if (visited == false) {
System.out.print(i);
}
i++;
System.out.println();
visited=false;
}
}
}
Not real groundbreaking, but why not!
Related posts:
Your first example is wrong: 15 will print ‘Fizz’, not ‘FizzBuzz’, because of your if else.
LOL. Good Catch! Once the 3 is validated as true, it will skip the elses.