Challenge: FizzBuzz
Completed
Read n and print the numbers 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 integer n.
Output
n lines.
Example
Input
15
Output
1 2 Fizz 4 Buzz Fizz 7 8 Fizz Buzz 11 Fizz 13 14 FizzBuzz
Editor
C++
Hints
i % 3 == 0 means i is a multiple of 3.
Check the "both" case (multiple of 15) first!
Solution explanation
The order of the checks matters: if you test for 3 first, 15 would print Fizz and never reach FizzBuzz.
Show solution
#include <iostream>
using namespace std;
int main() {
int n;
cin >> n;
for (int i = 1; i <= n; i++) {
if (i % 15 == 0) {
cout << "FizzBuzz\n";
} else if (i % 3 == 0) {
cout << "Fizz\n";
} else if (i % 5 == 0) {
cout << "Buzz\n";
} else {
cout << i << "\n";
}
}
return 0;
} 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