FizzBuzz Java Program

This Java program prints numbers from 1 to 100, but for multiples of 3, it prints “Fizz” instead of the number, for multiples of 5, it prints “Buzz”, and for multiples of both 3 and 5, it prints “FizzBuzz”.

Program Explanation

The program uses a loop to iterate through numbers from 1 to 100. Within the loop, it uses conditional statements to check whether the current number is a multiple of 3, 5, or both. Depending on the condition, it prints “Fizz”, “Buzz”, “FizzBuzz”, or the number itself.

Java Code

        /**
         * The FizzBuzz program prints numbers from 1 to 100 with the following conditions:
         * - Prints "Fizz" for multiples of 3
         * - Prints "Buzz" for multiples of 5
         * - Prints "FizzBuzz" for multiples of both 3 and 5
         */
        public class FizzBuzz {
            public static void main(String[] args) {
                // Loop through numbers from 1 to 100
                for (int i = 1; i <= 100; i++) {
                    // Check if the number is a multiple of both 3 and 5
                    if (i % 3 == 0 && i % 5 == 0) {
                        System.out.println("FizzBuzz");
                    }
                    // Check if the number is a multiple of 3
                    else if (i % 3 == 0) {
                        System.out.println("Fizz");
                    }
                    // Check if the number is a multiple of 5
                    else if (i % 5 == 0) {
                        System.out.println("Buzz");
                    }
                    // If none of the above, print the number itself
                    else {
                        System.out.println(i);
                    }
                }
            }
        }

Program Structure

  • Class Definition: The program defines a class named FizzBuzz.
  • Main Method: The main method is the entry point of the program.
  • Loop: A for loop is used to iterate through numbers from 1 to 100.
  • Conditionals: Inside the loop, if-else statements check if the current number is a multiple of 3, 5, or both, and print the appropriate message.

 

By Aditya Bhuyan

I work as a cloud specialist. In addition to being an architect and SRE specialist, I work as a cloud engineer and developer. I have assisted my clients in converting their antiquated programmes into contemporary microservices that operate on various cloud computing platforms such as AWS, GCP, Azure, or VMware Tanzu, as well as orchestration systems such as Docker Swarm or Kubernetes. For over twenty years, I have been employed in the IT sector as a Java developer, J2EE architect, scrum master, and instructor. I write about Cloud Native and Cloud often. Bangalore, India is where my family and I call home. I maintain my physical and mental fitness by doing a lot of yoga and meditation.

Leave a Reply

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

error

Enjoy this blog? Please spread the word :)