C++ bootcamp · Lab 10

FizzBuzz

mediumFor Loop12 minLesson: For Loop

Read the question, write C++ on the right, then Run or Check.

QuestionHint and solution stay closed until you open them

Read n and print the numbers 1 to n, one per line.

Replace multiples of 3 with Fizz, multiples of 5 with Buzz, and multiples of both with FizzBuzz.

Input. One line: an integer n ≥ 1.

Output. n lines of numbers or Fizz/Buzz/FizzBuzz.

Constraints

  • 1 ≤ n ≤ 100

Examples

Example 1
Input
5
Output
1
2
Fizz
4
Buzz
Hint
  1. Test divisibility by 15 first — a multiple of both must be handled before the single checks.
  2. i % 3 == 0 detects multiples of 3.
Show correct code

Peek only after you have tried. You can still Check your own version.

#include <iostream>

int main() {
  int n;
  std::cin >> n;
  for (int i = 1; i <= n; i++) {
    if (i % 15 == 0) std::cout << "FizzBuzz\n";
    else if (i % 3 == 0) std::cout << "Fizz\n";
    else if (i % 5 == 0) std::cout << "Buzz\n";
    else std::cout << i << "\n";
  }
  return 0;
}
main.cppC++17 · g++ · Ctrl + Enter runs
ResultIdle
Run to see output. Check grades the tests.