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.