C programming. The FizzBuzz program

leocod picture leocod · Feb 27, 2012 · Viewed 47.2k times · Source

I had a quiz and I wrote this code:

Print Fizz if it is divisible by 3 and it prints Buzz if it is divisible by 5. It prints FizzBuss if it is divisible by both. Otherwise, it will print the numbers between 1 and 100.

But after I arrived home, I wondered if could have writen it with less code. However, I could not come out with a shorter code. Can I do it with a shorter code? Thanks.

This is what I wrote and I think it works well. But can I have done it with less code.

#include <stdio.h>

int main(void)
{
    int i;
    for(i=1; i<=100; i++)
    {
        if(((i%3)||(i%5))== 0)
            printf("number= %d FizzBuzz\n", i);
        else if((i%3)==0)
            printf("number= %d Fizz\n", i);
        else if((i%5)==0)
            printf("number= %d Buzz\n", i);
        else
            printf("number= %d\n",i);

    }

    return 0;
}

Answer

martiert picture martiert · Feb 27, 2012

You could also do:

#include <stdio.h>

int main(void)
{
    int i;
    for(i=1; i<=100; ++i)
    {
        if (i % 3 == 0)
            printf("Fizz");
        if (i % 5 == 0)
            printf("Buzz");
        if ((i % 3 != 0) && (i % 5 != 0))
            printf("number=%d", i);
        printf("\n");
    }

    return 0;
}

A few lines shorter, and a lot easier to read.