Here's my code for Codecamedy's FizzBuzz lesson
var i;
for ( i = 1; i > 20; i++ ) {
"hello"
if ( i % 3 === 0 ) {
if ( i % 5 === 0 ) {
"FizzBuzz";
}
else {
"Fizz";
}
}
else if ( i % 5 === 0 ) {
"Buzz";
}
else {
i;
}
}
I'm trying to first test whether or not the number (i) is divisible by 3. If it is, I then want to check whether it is also divisible by 5. If both conditions are true, I want it to say "FizzBuzz". If only the first condition is true, it should say "Fizz". Then, after determining that i is not divisible by 3, it should check whether i is divisible by 5 and show "Buzz" if that's the case. Failing all divisibility, it should just show the number.
As I expected... it doesn't work as expected. What terribly embarrassing mistakes have I made?
Just for the sake of shortness, let's do it in one line:
The goal is to print "Fizz" for numbers that are integral divisible by 3 (without a rest), "Buzz" by 5 and "FizzBuzz" by 3 and 5, else it should print the number.
as modulo can return 0, we need to remember truthy and falsy values - 0 is a falsy value, therefore we need to negate the test if we want to check if a number is "truly" 0
e.g.: !(3 % 3) => !(0) => !false => true
Your specific problems are that you have the wrong sense for the
for
loop and that a statement like"somestring"
ori
doesn't actually do anything. What you want to do is output it do the console (or other output stream of some sort) - how to do this depends on the environment your Javascript is running in, and where you want the information to go.You can also keep in mind that any number evenly divisible by both three and five is a multiple of 15.
So you can simplify your code with something like:
There are those that will complain about multiple exit or restart points in a loop but you can safely ignore them since they don't understand the reasons behind that guideline, to avoid spaghetti code.
Any code where you can see all the control flow on a single page (such as the eleven lines above) is incapable of being spaghetti code, especially given the consistent handling.
Here's the equivalent Javascript code, packaged into a web page for testing:
which outputs, as desired:
My solution:
After considering all the other very good answers here:
Since you're "stuck on step 1" with the code you've provided, I assume you did the same mistake I did after clicking your link and reading the instructions. Step 1 doesn't actually ask you to solve the Fizzbuzz problem. To pass this step, you only have to do something much simpler. Read the (not very good) instructions again ;)
What if we make things a bit more difficult? 1) No division or modulo operations allowed; 2) The loop must skip all unnecessary iterations. Here is the answer: