Recursive FizzBuzz in C

Recursive FizzBuzz in C
0

#1

So, I couldn’t sleep, and started playing around in repl.it. Came up with this recursive FizzBuzz in C:

#include <stdio.h>

void fizzBuzz(int n);

int main(void)
{
  fizzBuzz(100);
}

void fizzBuzz(int n)
{
  if (n == 0)
    return;

  fizzBuzz(n-1);

  int f, b;

  if (!(f = n%3))
    printf("Fizz");
  if (!(b = n%5))
    printf("Buzz");
  if (f && b)
    printf("%i", n);
  printf("\n");
}

It’s probably not the most efficient way to do it, but it does work. Anybody have any thoughts on it?

Also, am I the only weirdo that writes random algorithms in C just to see if they can do it?


#2

Why have the variable assignment here? It seems like just testing n%3 and n%5 would be enough, but I don’t actually code much in C so maybe I’m missing some quirk of the language.

Great work, though.


#3

Thank you.

Actually, the first version of those lines was:

if(!(n%3))
  printf("Fizz");
if(!(n%5))
  printf("Buzz");
if (n%3 && n%5)
  printf("%i", n);

Then I decided to experiment, and prematurely optimized the code with the variables. It probably doesn’t really take any longer to do the modulo operation than the variable lookup. It might even be faster.

I was also curious if an assignment expression returns the assigned value in C, the same way it does in JS. Turns out it does.

And I left it because I thought the if (f && b) was amusing (I currently work in the Food & Beverage industry).