basics · beginner · ~15 min

FizzBuzz to N

Combine a for-loop with chained conditionals — and learn that case ORDER matters.

Challenge

Build the classic FizzBuzz sequence for 1..n as a single text buffer.

Task

Implement void fizzbuzz(int n, char *out, size_t out_sz) that writes the FizzBuzz lines for 1..n into the caller-provided buffer out (capacity out_sz bytes, including the terminating NUL). No main — the grader calls it.

Input

  • n: the upper bound, inclusive. May be 0 (produce nothing).
  • out: a writable buffer of out_sz bytes that you fill with a NUL-terminated string.

Output

Nothing is returned. After the call out holds one entry per line for i = 1..n, each followed by a \n:

  • i divisible by 15 -> FizzBuzz
  • else divisible by 3 -> Fizz
  • else divisible by 5 -> Buzz
  • otherwise the decimal number itself.

Example

fizzbuzz(5, out, sz)   ->   out = "1\n2\nFizz\n4\nBuzz\n"

Edge cases

  • n = 0: out becomes the empty string "".
  • Check divisibility by 15 before 3 and 5, or multiples of 15 are mislabelled.

Rules

  • Never write past out_sz; use bounded formatting (e.g. snprintf with a running offset).

Why this matters

The most-asked screening question in the world. Get it precise once and it's a freebie forever.

Input format

n (inclusive upper bound) plus a writable buffer out of out_sz bytes.

Output format

out filled with the FizzBuzz lines for 1..n, each ending in newline, NUL-terminated.

Constraints

Check divisibility by 15 first; never write past out_sz.

Starter code

#include <stdio.h>
#include <string.h>

void fizzbuzz(int n, char *out, size_t out_sz) {
    /* TODO */
    out[0] = '\0';
}

Common mistakes

Wrong case order (15 misclassified as Fizz). Off-by-one (100 missing). Forgetting else.

Edge cases to handle

i=15, 30, 45, 60, 75, 90 → FizzBuzz. i=100 must be included (loop bound is <= 100).

Complexity

O(N).

Background lessons

Up next

Solve this exercise in the browser editor — compile and run against the test harness, no setup required.