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;
}
I'm not sure when you'd start calling it unreadable, but there's this.
You could also do:
A few lines shorter, and a lot easier to read.
I'd go with a helper function :-)
i would write something like that
I would say that modulo is expensive while comparisons are cheap so only perform the modulo once. That would yield something like this.