Skip to content

Instantly share code, notes, and snippets.

@theoboldalex
Created April 28, 2023 06:51
Show Gist options
  • Select an option

  • Save theoboldalex/b13b925b276d61ead5f1d3b610fe41bf to your computer and use it in GitHub Desktop.

Select an option

Save theoboldalex/b13b925b276d61ead5f1d3b610fe41bf to your computer and use it in GitHub Desktop.
FizzBuzz without strings in C
#include <stdio.h>
#include <math.h>
#define LIMIT 100
#define LF 10
#define ASCII_ZERO 48
void printFizz();
void printBuzz();
void printNumber(int number);
int fizzBuzzCharCodes[] = {70, 105, 122, 122, 66, 117, 122, 122};
size_t fizzBuzzLength = sizeof(fizzBuzzCharCodes) / sizeof(int);
int main(void) {
for (int i = 1; i <= LIMIT; i++) {
if (i % 15 == 0) {
printFizz();
printBuzz();
putchar(LF);
} else if (i % 3 == 0) {
printFizz();
putchar(LF);
} else if (i % 5 == 0) {
printBuzz();
putchar(LF);
} else {
printNumber(i);
putchar(LF);
}
}
}
void printFizz() {
for (int i = 0; i < fizzBuzzLength / 2; i++) {
putchar(fizzBuzzCharCodes[i]);
}
}
void printBuzz() {
for (int i = fizzBuzzLength / 2; i < fizzBuzzLength; i++) {
putchar(fizzBuzzCharCodes[i]);
}
}
void printNumber(int number) {
int digitCount = 0;
int limitLength = (int) log10(LIMIT) + 1;
int digits[limitLength];
while (number > 0) {
int mod = number % 10;
digits[digitCount] = mod;
digitCount++;
number = number / 10;
}
for (int i = digitCount - 1; i >= 0; i--) {
putchar(digits[i] + ASCII_ZERO);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment