And the good... but I need help


#1

<PLEASE USE THIS TEMPLATE TO HELP YOU CREATE A GREAT POST!>

<Below this line, add a link to the EXACT exercise that you are stuck at.>

<Below this line, in what way does your code behave incorrectly? Include ALL error messages.>
It will only return the numbers then the word fizz

```

Replace this line with your code.
for (i = 1; i < 21; i++){
console.log(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);
}

<do not remove the three backticks above>

#2

It will only return the numbers then the word fizz

that is because of your for loop

for (i = 1; i < 21; i++){
console.log(i); //prints from 1 to 20
}

and here

else if((i % 3)=== 0){
console.log("Fizz"); // now i=21 so it's true.
}

so it prints Fizz

after completing the loop it goes to if else statement. but at each iteration it should go for checking.


#3

So how should I modify it so that it checks each iteration, but then continues.


#4

Hi @mathrebel13,

You need to nest your if/else if/else statements into the loop.

So when your loop runs, beginning at i=1, it will check whether it fulfills the condition to print “FizzBuzz”, “Buzz” or “Fizz”, if those condition not fulfilled, it will only print the number i which is 1.

Then, the loop will start the process again at i=2, check the whole conditions, print what is corresponding to the condition.

Next, loop starts at i=3, check the conditions, it fulfilled else if((i % 3)=== 0), thus, “Fizz” is printed.

The loop will keep doing this repeatedly until i<21.


What you’ve been missing is that your if/else if/else statement is outside of the loop.

Delete the first console.log(i), then replace that with the whole if/else if/else statements inside the loop.

Then it will work. Cheers :slight_smile:


#5

Thank you very much, my code did end up working.


#6

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