FizzBuzz

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:

package FizzBuzz;

/*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):

package FizzBuzz;

/*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!

Facebook Twitter Linkedin

Related posts:

  1. Java Drop-down Dialog

About Mike

I am a Software Quality Assurance Professional that recently graduated college with a Bachelor's of Science in Computer Information Systems.
This entry was posted to the following categories: Code Sample, Java. Bookmark the permalink.

2 Responses to FizzBuzz

  1. Tom says:

    Your first example is wrong: 15 will print ‘Fizz’, not ‘FizzBuzz’, because of your if else.

  2. Mike says:

    LOL. Good Catch! Once the 3 is validated as true, it will skip the elses. :)

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>