FizzBuzz


#1

I have a question..
1. if I code like this:

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

console.log(number);

it doesnt print out "FizzBuzz",

  1. if I code it like this:

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

console.log(number);

it doesn't print Buzz by 20.

What is wrong in my code?


#2

Your code works correctly. Because you already catch the case which is not quite as detailed.

for(var number = 1; number < 20; number++)
{
if( number % 3 === 0 ) { console.log("Fizz"); } // i = 15 log Fizz and END
else if( number % 5=== 0 ) { console.log("Buzz"); } // i= 10 log Buzz and END
else if(number%3===0 && number%5===0) { console.log("FizzBuzz"); } // you never reach this part 
else {console.log(number)}
};

Make first the more detailed query.

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

#3

danke! :slight_smile: === thanks :slight_smile:


#4

you are welcome === "Bitte schön" :slight_smile:


#5

i want to explain this in a bit more detail, even though the issue has been resolved.

if you have an if/else if/else clause, if the if condition evaluates to true, the else if and else will never run.

so if you have a number which is divisible by 3 and 5, of course it is divisible by 3 (your if condition) so it never gets to checking if the number is divisible by 3 and 5, so checking if the number is a fizzbuzz should be your if condition


#6

aah okay I thought about it but I wasn't sure, thank you! :relieved:


#7

i a way it makes sense:
if true: do this
else if true: do this
else: do this

so it make sense that if if is true, else if and else don't execute


#8

So, the answer of your question is:
You didn't print Buzz at 20, because your for loop goes to less then 20 ( <20).
For loop should be like this:

for (var number = 1; number <= 20; number++)

You should either type (less then 21) or <=20. :wink:


#9

but this code is not getting executed


#10

please make your own topic so someone can help you


#11

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