Skip to main content

fizzbuzz — FizzBuzz in C

Allowed functions: write

Write a program that prints the numbers from 1 to 100, each separated by a newline.

  • If the number is a multiple of 3, it prints fizz instead.
  • If the number is a multiple of 5, it prints buzz instead.
  • If the number is both a multiple of 3 and a multiple of 5, it prints fizzbuzz instead.

Examples

$>./fizzbuzz
1
2
fizz
4
buzz
fizz
7
8
fizz
buzz
11
fizz
13
14
fizzbuzz
[...]
97
98
fizz
buzz

Solution

Download fizz_buzz.c
#include <unistd.h>

void putnumber(int n) {

char c;

if (n >= 10)
putnumber(n / 10);

c = n % 10 + '0';
write(1, &c, 1);
}

int main() {
int n = 1;

while (n <= 100) {

if (n % 5 == 0 && n % 3 == 0) {

write(1, "fizzbuzz", 8);
}

else if (n % 5 == 0) {
write(1, "buzz", 4);
} else if (n % 3 == 0) {
write(1, "fizz", 4);
}

else {
putnumber(n);
}
write(1, "\n", 1);
n++;
}

return 0;
}

How It Works

Goal: Print numbers 1 to 100, but replace multiples of 3 with "fizz", multiples of 5 with "buzz", and multiples of both with "fizzbuzz".

Approach: Loop from 1 to 100 and use the modulo operator (%) to check divisibility. A helper function putnumber handles printing multi-digit numbers since we can only use write.

Step by step:

  1. putnumber converts an integer to characters recursively:

    • If n >= 10, it calls itself with n / 10 to handle higher digits first
    • Then it converts the last digit to a char with n % 10 + '0' and writes it
    • Example: putnumber(42) → calls putnumber(4) → writes '4' → returns → writes '2'
  2. In main, we loop n from 1 to 100:

    • Check n % 5 == 0 && n % 3 == 0 first — this must come before the individual checks, otherwise 15 would print "fizz" instead of "fizzbuzz"
    • Then check n % 5 == 0 for "buzz"
    • Then check n % 3 == 0 for "fizz"
    • Otherwise, print the number using putnumber
    • After each case, write a newline

Key concept: The modulo operator % returns the remainder of a division. If n % 3 == 0, then n is evenly divisible by 3. The order of conditions matters — always check the combined case first.