FizzBuzz?


#1

I have problem here :confused:

This code doesnt work because when counter finds 15 insted of print FizzBuzz he print just Fizz!!
Can some1 tell where did i go wrong.
There is my code ===>

var numbers = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20];
for (var i = 0; i < numbers.length; i++) {
    if ( numbers[i] % 3 === 0 ) {
            console.log("Fizz")
    }   else if (numbers[i] % 5 === 0) {
            console.log("Buzz")
    }   else if ((numbers[i] % 3 === 0) && (numbers[i] % 5 === 0 )) {
            console.log("FizzBuzz") 
    }   else {
            console.log(numbers[i])
    }
}

I think that code is perfect :smile:


#2

Your code is good, the only problem is in where you place your conditions you need to check first it it is a multiple by 3 and 5 together then check for other conditions.


#3

Close, but I don't think that this:

  else if ((numbers[i] % 3 === 0) && (numbers[i] % 5 === 0 )) {
            console.log("FizzBuzz") 
    }

Will ever run.

Else-If Statements will run the first thing they run into, so I'd suggest putting this before every other if statement.


#4

ok, thx for quick response, but i need to know why is so important which else-if statment is writen first and also when i write some other else-if statment how will i know what statment frist to write???


#5

ok, thx for quick response, but i need to know why is so important which else-if statment is writen first and also when i write some other else-if statment how will i know what statment frist to write?


#6

Here's my code:

for (var i = 1; i <= 20; 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 % 3 === 0 && i % 5 ===0) {console.log("FizzBuzz"); }
else {console.log(i); }
}

I initially ran into the same problem as you did. I found when I specified that "i" did NOT equal 0 in addition to saying that "i" did equal zero alleviated the problem. I'm not exactly sure why this is though.


#7

Is it giving you a problem? or are you passing the lesson with that?


#8

So basically your code for the & condition won't ever run because in the if else if statements you need to see which one is highest priority and that is the and condition that way you will be left with 3 OR 5 since its not both. That way your code will run fine. Does that make sense?


#9

This code worked for me. I originally ran into the problem where it didn't print "FizzBuzz" at 15 but putting that condition first worked. They next issue I had was that it "printed the wrong number of items to the console. I fixed this by putting i = 1. The instructions specify to iterate through numbers 1 - 20, not 0 - 20.

for (var i = 1; i <= 20; i++) {
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)
}
}


#10

yes i am, thx for your help!!