Java FizzBuzz Program



In this post, we will write a Java program to implement the FizzBuzz game.

FizzBuzz is a game that is popular among kids. By playing this, kids learn the division. Now, the FizzBuzz game has become a popular programming question that is frequently asked in Java programming interviews. In this section, we will learn how to create a FizzBuzz program in Java.

Rules of the FizzBuzz Game

The rules of the FizzBuzz game are very simple.

Say Fizz if the number is divisible by 5.

Say Buzz if the number is divisible by 7.

Say FizzBuzz if the number is divisible by both 5 and 7.

Return the number itself, if the number is not divisible by 5 and 7.

Java FizzBuzz Program


public class FizzBuzz{

     public static void main(String []args){
        FizzBuzz.print(100);
     }
     
     public static void print(int n) {

        for (int i = 1; i <= n; i++) {
            if (((i % 5) == 0) && ((i % 7) == 0)) { // multiple of 5 & 7            
                System.out.println("fizzbuzz");
            } else if ((i % 5) == 0) { // multiple of 5            
                System.out.println("fizz");
            } else if ((i % 7) == 0) { // multiple of 7            
                System.out.println("buzz");
            } else {
                System.out.println(i); // not a multiple of 5 or 7
            }
        }
    }
}

Comments