FizzBuzz in Java

Description: Print the numbers from 1 to 15. For multiples of 3 print Fizz, for multiples of 5 print Buzz, and for multiples of both print FizzBuzz.

Hint:

  • Check the multiples of 15 (both) first.

Solution

public class Main {
    public static void main(String[] args) {
        for (int i = 1; i <= 15; i++) {
            if (i % 15 == 0) {
                System.out.println("FizzBuzz");
            } else if (i % 3 == 0) {
                System.out.println("Fizz");
            } else if (i % 5 == 0) {
                System.out.println("Buzz");
            } else {
                System.out.println(i);
            }
        }
    }
}
Output

1
2
Fizz
4
Buzz
Fizz
7
8
Fizz
Buzz
11
Fizz
13
14
FizzBuzz

How it works

  • If you check 3 first, then 15 would print only Fizz. So the most special case must come first.

Read Java for Loop.


Learn more about the similar topics:
Tutorials
No Content Found.
Exercises & Assignments
No Content Found.
Interview Questions & Answers
No Content Found.