The nifty thing about this month’s Exercise is that so many solutions are available. In fact, I found the challenge engaging because I kept trying to think of other ways to solve the puzzle.
To be successful, the output your solution code generates looks something like this:
1
2
Fizz
4
Buzz
Fizz
7
8
Fizz
Buzz
11
Fizz
13
14
FizzBuzz
16
17
And on up to 100. The output must be consistent no matter what your solution.
For my first crack, I did a straightforward loop with if tests to generate the Fizz and Buzz output:
#include <stdio.h>
int main()
{
int a;
for(a=1;a<=100;a++)
{
if( a % 3 == 0 )
printf("Fizz");
if( a % 5 == 0 )
printf("Buzz");
if( a%3 && a%5 )
printf("%d",a);
putchar('\n');
}
return(0);
}
The first if test outputs Fizz when a is divisible by 3, the second outputs Buzz when a is divisible by 5. Both tests pass for values divisible by both 3 and 5, so FizzBuzz is output.
The third if test is TRUE for all values not divisible by either 3 or 5. And finally, the putchar() function spits out a newline.
This solution was good, but I wanted something more cryptic!
After a few gyrations, I concocted another solution:
#include <stdio.h>
int main()
{
int a;
char buf[4];
for(a=1;a<=100;a++)
{
sprintf(buf,"%d",a);
printf("%s\n",
a%3 && a%5 ? buf :
a%3 ? "Buzz" :
a%5 ? "Fizz" :
"FizzBuzz"
);
}
return(0);
}
The sprintf() function converts the value of a into a string. It does this conversion for all values, though not every string created is output.
In the printf() function, a series of nested ternary operators generates the proper string to output. This construction is effectively a complex if-else test, though I formatted the code to put each initial test on a line by itself:
The first line is the same as the final if test in my first solution: If a is either divisible by 3 or 5, output the value of a, which is text stored in buf. Otherwise:
The second line generates Buzz when a is not equal to 3.
The third line generates Fizz when a is not equal to 5.
The final line outputs FizzBuzz because the only condition not tested for is a divided by 15, or both 3 and 5.
For more solutions, including some that will drive you mad, go to Rosetta Code’s FizzBuzz page, the C solution: http://rosettacode.org/wiki/FizzBuzz#C
I hope your solution is unique and interesting, and I further hope you crafted more than one as you got into the puzzle. That’s one of the nifty things about learning to program: This puzzle may not prevent world hunger, but working on such problems definitely increases your C programming kung fu, which may eventually prevent world hunger.