3. Can't find the problem for fizzbuzz


#1

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

It says I printed Fizz when I should I have printed FizzBuzz. I can't find a problem.


#2

@blondesquirrel
As per your code, while checking for 15, you will print "Fizz".
Although 15 is divisible by 3 and 5, as per you code, you doing the following:

  1. Check if a number is divisible by 3. If yes, print; else, go to next step.

  2. Check if a number is divisible by 5. If yes, print; else, go to next step.

  3. Check if the number is divisible by both 3 and 5. If yes, print.

While checking for 15, as per you code, it first checks if this number is divisible by 3. Since, the number is divisible by 3, Fizz is printed.
To correct your code, first check if a number is divisible by both 3 and 5.
Hope this helps!


#3

Thank you, you solved my problem, I'll have to keep the order of the if/else statements in mind.