basics · beginner · ~15 min
Combine a for-loop with chained conditionals — and learn that case ORDER matters.
FizzBuzz is the interview-screening exercise that filters out people who can't write a simple loop. It's deliberately not hard — but it teaches you to be precise about exactly which condition fires first.
Write a program that prints the numbers 1 through 100, one per line, with these substitutions:
FizzBuzz.Fizz.Buzz.int main(void);
100 lines. Each is one of: FizzBuzz, Fizz, Buzz, or a number 1–100.
Fizz for 15 (wrong).for loop from 1 to 100 inclusive.printf per iteration.| n | output |
|---|---|
| 1 | 1 |
| 3 | Fizz |
| 5 | Buzz |
| 15 | FizzBuzz |
| 30 | FizzBuzz |
| 100 | Buzz |
if checks matters. if (n % 3 == 0) is true for 15, so check the AND case first.for (int i = 1; i <= 100; i++) { … }. Inside, check (i % 15 == 0) first, then % 3, then % 5, else print the number.if (i % 3 == 0 && i % 5 == 0) separately AND then if (i % 3 == 0) without else. Both fire for 15 and you double-print.else chain — multiple prints for FizzBuzz numbers.if/else if ladder but checking % 3 before % 15. The 15-multiples then misclassify as Fizz.After this, you can read any for-loop + chained conditional in real C without flinching. The discipline of "check the most specific case first" is the same as the case ordering in a real switch or in tighter pattern-matching code.
The most-asked screening question in the world. Get it precise once and it's a freebie forever.
No input.
100 lines, one per number 1..100.
Check the 15-divisible case first. Inclusive of 100. One printf per iteration.
#include <stdio.h>
#include <string.h>
void fizzbuzz(int n, char *out, size_t out_sz) {
/* TODO */
out[0] = '\0';
}
Wrong case order (15 misclassified as Fizz). Off-by-one (100 missing). Forgetting else.
i=15, 30, 45, 60, 75, 90 → FizzBuzz. i=100 must be included (loop bound is <= 100).
O(N).
Solve this exercise in the browser editor — compile and run against the test harness, no setup required.