Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C programming. The FizzBuzz program [closed]

Tags:

c

fizzbuzz

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;
}
like image 554
leocod Avatar asked Feb 27 '12 07:02

leocod


2 Answers

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.

like image 144
martiert Avatar answered Nov 05 '22 23:11

martiert


I'm not sure when you'd start calling it unreadable, but there's this.

#include <stdio.h>

int main(void)
{
   int i = 1;
   for (; i<=100; ++i) {
      printf("number= %d %s%s\n", i, i%3?"":"Fizz", i%5?"":"Buzz");
   }
   return 0;
}
like image 45
Mr Lister Avatar answered Nov 05 '22 23:11

Mr Lister