3. FizzBuzz help, why won't it work?

#1

I'm using this code below and it's telling me "Oops, try again. It looks like you printed out the wrong number of items."
even though it looks to me like it's printing the exact number it wanted me to? This is what it prints:

1
2
Fizz
4
Buzz
Fizz
7
8
Fizz
Buzz
11
Fizz
13
14
FizzBuzz
16
17
Fizz
19
Buzz

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

#2

set `i` to 0 when you define your variable, then start from 1 in your for loop.

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

#3

Whats the use of assigning 0 to i; when you eventually override it to 1 in your for loop ?

#4

Why does this particular code only prints "FizzBuzz" when logical operator && is in "if" statment and not in "else if"?

#5

Yes I would like to know the answer to that!

#6

#7

Because once a condition is true, it doesn't fall through to the next condition. Use multiple ifs if you want that

#8

Once one of the conditions in the if (...) / else if (...) is true (from top to bottom), the rest of the conditions are not evaluated and the program goes into the next loop (next i) value.

#9

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.