Challenge: FizzBuzz
Completed
Read n and print the numbers from 1 to n, one per line. But for multiples of 3 print Fizz, for multiples of 5 print Buzz, and for multiples of both print FizzBuzz.
Input
One whole number n.
Output
n lines.
Example
Input
15
Output
1 2 Fizz 4 Buzz Fizz 7 8 Fizz Buzz 11 Fizz 13 14 FizzBuzz
Editor
Java
Hints
Check "both" first: a multiple of 3 and 5 is a multiple of 15.
i % 3 == 0 means i is a multiple of 3.
Solution explanation
Order matters: if you checked % 3 first, 15 would print Fizz and never reach FizzBuzz.
Show solution
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
for (int i = 1; i <= n; 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
Answer
You can practice without logging in. Log in to save completion.
Save your progress
You're practising as a guest, so your progress won't be saved.
- Track every lab you complete
- Earn verifiable lab certificates
- See your progress in every module