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
fizzinstead. - If the number is a multiple of 5, it prints
buzzinstead. - If the number is both a multiple of 3 and a multiple of 5, it prints
fizzbuzzinstead.
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:
-
putnumberconverts an integer to characters recursively:- If
n >= 10, it calls itself withn / 10to handle higher digits first - Then it converts the last digit to a char with
n % 10 + '0'and writes it - Example:
putnumber(42)→ callsputnumber(4)→ writes'4'→ returns → writes'2'
- If
-
In
main, we loopnfrom 1 to 100:- Check
n % 5 == 0 && n % 3 == 0first — this must come before the individual checks, otherwise15would print "fizz" instead of "fizzbuzz" - Then check
n % 5 == 0for "buzz" - Then check
n % 3 == 0for "fizz" - Otherwise, print the number using
putnumber - After each case, write a newline
- Check
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.