Java code solve Fizz Buzz Problem

How to solve Fizz Buzz Problem  in Java before dive into the code let’s understand what is the fizz buzz problem in Java

Fizz buzz problem in Java

Problem Statement:

a) Print the no. from 1 to 100

b) For multiple of 3, print FIZZ instead of no.

c) For multiple of 5, print BUZZ instead of the no.

d) For multiple of 3 and 5 both, print FIZZ BUZZ instead of the no.

Algorithm for Fizz Buzz Problem:-

1) Make a for loop which runs from 1 to 100.

2) Declare a boolean variable fizz which evaluates to true if the no. is divisible by 3 else false.

3) Declare a boolean variable buzz which evaluates to true if the no. is divisible by 5 else false.

4) Now if fizz and buzz both are true, print FIZZ BUZZ.

5) If the above condition is not true and the only fizz evaluates to true, print FIZZ.

6) If the above condition is not true and the only buzz evaluates to true, print BUZZ.

7) Else print the no. itself.

Program for Fizz Buzz Problem:-

package com.test;
public class demo 
{
  public static void main(String[] args)
   {
      for(int i=1;i<=100;i++)
      {
        boolean fizz=(i%3==0);
        boolean buzz=(i%5==0);
        if(fizz && buzz) System.out.println("FIZZ BUZZ");
        else if(fizz) System.out.println("FIZZ");
        else if(buzz) System.out.println("BUZZ"); 
        else System.out.println(i);
      }
  }
}

The output of Fizz Buzz Problem:-

1
2
FIZZ
4
BUZZ
FIZZ
7
8
FIZZ
BUZZ


FIZZ BUZZ
91
92
FIZZ
94
BUZZ
FIZZ
97
98
FIZZ
BUZZ