Need help with FizzBuzz


#1
for (var i = 1; i < 21; i++) {
if(i%3 === 0){
    console.log("Fizz");
}
else if (i%5 === 0){
    console.log("Buzz");
}
 else if (i%3 === 0 && i%5 === 0){
    console.log("Buzz");
}
else {
    console.log(i);
}
};

Here is the output.
1
2
Fizz
4
Buzz
Fizz
7
8
Fizz
Buzz
11
Fizz
13
14
Fizz
16
17
Fizz
19
Buzz

I'm getting a message that I printed Fizz when I should have printed FizBuzz. I think the problem occurs
when it tries to print number 15. I cannot figure out what is wrong.


#2
 else if (i%3 === 0 && i%5 === 0){
    console.log("Buzz");

There's your problem - I think you meant to write FizzBuzz :wink:


#3

@ismith98
I think the problem comes from here:

First, you should test whether the variable i is evenly divisible by 3 and 5. Your code:

On the first if statement, it already mets the condition so doesn't execute the rest of the code and will only print out "Fizz" (well, if variable i is evenly divisible by 3 and 5). The other else if should be printing "Fizz" or "Buzz" whether it is evenly divisible by 3 or 5. As @nedwards said, you must print "FizzBuzz" if it meets the two condition. Here you wrote:

Hope this helped you!


#4

You have to write your if/else code in this order
if (i % 3 === 0 && i % 5 === 0) {
console.log("FizzBuzz");
} else if (i % 5 === 0) {
console.log("Buzz");
} else if (i % 3 === 0) {
console.log("Fizz");
} else {
console.log(i);
}

Make sure your code checks to see if the variable is divisible by 3 and 5 first, or else it will only log either "Fizz" or "Buzz," then skip the rest of the if/else statements. I had this same problem.


#5

Thank you for that crew, but if I may ask, why that order instead of any other order. I wrote my code correctly and I believed beyond reasonable doubt it was okay but it did not log "FizzBuzz" while the condition was true. I came out here and your solution solved it. If you can just clarify on that, I will be greatful. Cheers.


#6

In if/else statements, the code will execute the first statement that meets its conditions.

So if you look at your original code, 15 is divisible by 3 and 5 with no remainder. However, the first condition it checks is this:

if(i%3 === 0){
    console.log("Fizz");
}

This is true, so it executes the block and doesn't need to check the others. This is why you should have it check for both of them first.


#7

I get it. Thanks, much appreciated.