The Fizz Buzz problem is a classic programming task often used in coding interviews to test basic programming skills. The task is to print numbers from 1 to a given number n, but for multiples of 3, print “Fizz” instead of the number, for multiples of 5, print “Buzz” instead of the number, and for numbers that are multiples of both 3 and 5, print “Fizz Buzz”.
Fizz Buzz Problem in Java:
Below is the simple implementation of the FizzBuzz problem in Java:
public class FizzBuzz {
public static void main(String[] args) {
int n = 100; // You can set n to any positive integer
for (int i = 1; i <= n; i++) {
if (i % 3 == 0 && i % 5 == 0) {
System.out.println("FizzBuzz"); // Multiple of both 3 and 5
} else if (i % 3 == 0) {
System.out.println("Fizz"); // Multiple of 3
} else if (i % 5 == 0) {
System.out.println("Buzz"); // Multiple of 5
} else {
System.out.println(i); // Neither multiple of 3 nor 5
}
}
}
}
Explanation:
- Loop from 1 to n:
- The loop iterates through each number from 1 to
n.
- The loop iterates through each number from 1 to
- Check Conditions:
- Multiple of both 3 and 5: Use
i % 3 == 0 && i % 5 == 0to check if the number is divisible by both 3 and 5, then print “FizzBuzz”. - Multiple of 3: Use
i % 3 == 0to check if the number is divisible by 3, then print “Fizz”. - Multiple of 5: Use
i % 5 == 0to check if the number is divisible by 5, then print “Buzz”. - Otherwise: Print the number itself if none of the above conditions are met.
- Multiple of both 3 and 5: Use
Key Points:
- The order of conditions matters: check for multiples of both 3 and 5 first (
i % 3 == 0 && i % 5 == 0), otherwise it would print “Fizz” or “Buzz” for numbers that are multiples of both before reaching the combined condition. - This approach runs in O(n) time complexity as it simply iterates from 1 to
nonce.