FiizBuzz is a simple game often used to challenge new coders skills and thinking ability. The rules are easy:
- Your program should print all the numbers from 1-100
- Any number which is a multiple of three should be printed as "Fizz" instead of the number
- Any number which is a multiple of five should be printed as "Buzz" instead of the number
- Any number which is a multiple of both three and five should be printed as "FizzBuzz"
HINT: To get the remainder of a divison use the modulo operator (%).
int remainder = 21%5;
//remainder would be equal to 1 as 21/5 gives a remainder of one
See the solution
There a number of different way to solve this so lets brake each one down. The most common way for new programmers probably resemble something like the following:
for(int i = 0; i <=100, i++){
if(i%15 == 0) {
print("FizzBuzz");
} else if(i%3 == 0){
print("Fizz");
} else if (i%5 == 0) {
print("Buzz");
} else {
print(i.ToString());
}
}
Now this works, however I do not believe it to be the clearest to read. Try:
for(int n = 0; n <= 100; n++) {
string result = "";
if (n%3 == 0) {
result += "Fizz";
}
if (n%5 == 0) {
result += "Buzz";
}
if (result == ""){
result = n.ToString();
}
print(result);
}
Whilst it is technically possible to all the testing on one line, it is rarely advised:
for(int i = 0; i <= 100; i++) {
print(i%15 ? "FizzBuzz" : i%3 ? "Fizz" : i%5 ? "Buzz" : i.ToString());
}
For further clarity, we could write all of our testing logic in a method and call that from our for loop. This will simplify the reading of our code dramatically.
// Inside our 'Main' or 'Start' method
for(int n = 0; n <= 100; n++) {
print(FizzBuzz(n));
}
// Somewhere in our code base
public static string FizzBuzz(int n) {
string result = "";
if (n%3 == 0) {
result += "Fizz";
}
if (n%5 == 0) {
result += "Buzz";
}
if (result == ""){
result = n.ToString();
}
print(result);
}