Here is a description of the FizzBuzz problem as stated in this Jeff Atwood article.
Write a program that prints the
numbers from 1 to 100. But for
multiples of three print "Fizz"
instead of the number and for the
multiples of five print "Buzz". For
numbers which are multiples of both
three and five print "FizzBuzz".
A ternary operator is shorthand writing for an if-else statement. The general format is:
cond ? evaluate_if_cond_is_true : evaluate_if_cond_is_false
So if I write:
int isEven = (i % 2 == 0) ? 1 : 0;
Is equivalent to the following code:
if (i % 2 == 0) {
isEven = 1;
} else {
isEven = 0;
}
Where cond is i % 2 == 0
, evaluate_if_cond_is_true is 1
and evaluate_if_cond_is_false is 0
.
The nice thing about ternary operators is that they can be combined. This means that the statement to execute when either condition evaluates to true or false can be another ternary operator.
Let put the entire condition in a more readable fashion:
i%3==0 ?
i%5==0 ?
"FizzBuzz"
: "Buzz"
: i%5==0 ?
"Fizz"
: i
And mapping this to if-else statements is easy with the rules explained above:
if (i%3==0) {
if (i%5==0) {
"FizzBuzz"
} else {
"Buzz"
}
} else {
if (i%5==0) {
"Fizz"
} else {
i
}
}
This is not valid code but because the result of the ternary operator is inlined in the result expression it is used as input for the puts command.