If else

#1

this is really strange
can u please look at this

for (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("FizzBuzz");
} else {
console.log(i);
}``````

};

it says [Oops, try again. You printed Fizz when you should have printed FizzBuzz]

y?
thanks everybody

#2

Hi @reefoo

You have to put the FizzBuzz condition in first, because it's the first condition who will be read by the program

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

Hold on

#3

yes true

but dont get it though

thank u very much

#4

Let's pretend we're the computer and maybe that'll explain it to you!

ok For this example I'm going to pretend the "i" is 15!

So this is what the code sees:

``````for (i = 1; i < 21; i++){ //i is less than 21
if(i % 3 === 0 && i % 5 === 0){ //i is equal to the modulo of 3 AND 5
console.log("FizzBuzz");
/*  }else if(i % 3 === 0){      -Else if statements only go if one of the-
console.log("Fizz");    -if statements before it hasn't been used-
}else if(i % 5 === 0){      -This means the rest of the "else-if"    -
console.log("Buzz");    -Statements are being skipped!
}else{
console.log(i);
}   */
};``````

For the next example let's pretend that i is equal to 9:

``````for (i = 1; i < 21; i++){ //i is less than 21
/*  if(i % 3 === 0 && i % 5 === 0){
console.log("FizzBuzz");  */
}else if(i % 3 === 0){ //"i" is equal to the null modulo of 3!
console.log("Fizz");
/*  }else if(i % 5 === 0){    -The rest of the else-if and else statements-
console.log("Buzz");  -won't be seen by the console.              -
}else{
console.log(i);
}   */
};``````

Last example! "i" is now equal 19!

``````for (i = 1; i < 21; i++){ //i is less than 21!
/*  if(i % 3 === 0 && i % 5 === 0){
console.log("FizzBuzz");
}else if(i % 3 === 0){
console.log("Fizz");
}else if(i % 5 === 0){
console.log("Buzz"); */
}else  //19 doesn't have a null remainder after being devided by 5 or 3
console.log(i); //Just print this number! (19)
}
};``````

If anything I said doesn't make sense please let me know and I'll explain it further!

#5

ok i got it now

coz my link doesnt give any chance for the fizzbuzz to happen since all possible numbers will be used on %3
or %5 before
yes make sense

thank u very much

appreciated