cfizzbuzz

Fizzbuzz program in C


Okay, this really isn't as much a fizzbuzz question as it is a C question.

I wrote some simple code in C for printing out fizzbuzz as is required.

#include <stdio.h>

int main(void)
{
    int n = 30;
    int i;
    for (i = 1; i<=n; i++)
        printf("%s\n", (i % 15) == 0 ? "fizzbuzz" : (i % 5) == 0 ? "buzz" : (i % 3) == 0 ? "fizz" : i);
}

Now, the last else statement obviously doesn't work since printf is accepting a string whereas 'i' is an int. My question is, is there any sort of cast that I can apply to convert the 'i' into a string?

EDIT: I should mention, what I'm really asking is if this fizzbuzz test can be done using a single print statement. No particular reason why I want it to be a single print statement only other than curiosity of as to whether it can be done.

EDIT2: Question answered and here's my implementation:

#include <stdio.h>

int main(void)
{
    int i, n=30;        
    for (i = 1; i<=n; i++)
        printf((!(i%3) || !(i%5)) ? "%s\n" : "%d\n", !(i % 15) ? "fizzbuzz" : !(i % 5) ? "buzz" : !(i % 3) ? "fizz" : i);
}

http://codepad.org/DN7yBW99


Solution

  • You've cornered yourself by the way you've tried to put all the logic inside of the printf call. It would be better to write it out the "slow" way first, then look for ways to optimize it afterward.

    for (i = 1; i <= n; i++) {
        if (i % 15 == 0)
            printf("fizzbuzz\n");
        else if (i % 5 == 0)
            printf("buzz\n");
        else if (i % 3 == 0)
            printf("fizz\n");
        else
            printf("%d\n", i);
    }
    

    Addendum: Do it with just one printf...

    /* The following code is NOT recommended... */
    
    int isFizz     = (i % 3 == 0      ) ? 1 : 0;
    int isBuzz     = (i % 5 == 0      ) ? 1 : 0;
    int isFizzBuzz = (isFizz && isBuzz) ? 1 : 0;
    
    printf(
        (isFizz || isBuzz) ? "%s\n" : "%d\n",
        (
            isFizzBuzz ? "fizzbuzz" :
            isFizz     ? "fizz"     :
            isBuzz     ? "buzz"     :
            i
        )
    );
    

    http://codepad.org/LMr5WdIm