C bootcamp · Lab 15

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 <stdio.h>

int main(void) {
  int n;
  scanf("%d", &n);
  for (int i = 1; i <= n; i++) {
    if (i % 15 == 0) printf("FizzBuzz\n");
    else if (i % 3 == 0) printf("Fizz\n");
    else if (i % 5 == 0) printf("Buzz\n");
    else printf("%d\n", i);
  }
  return 0;
}
main.cC17 · gcc · Ctrl + Enter runs
ResultIdle
Run to see output. Check grades the tests.