Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Eloquent Javascript FizzBuzz

Tags:

javascript

I'm currently working through eloquent javascript.

I'm trying to do the fizzbuzz task, I'm struggling when having to print numbers divisible by 3 & 5.

Task and my solution so far below.

Cheers.

Task:

Write a program that uses console.log to print all the numbers from 1 to 100, with two exceptions. For numbers divisible by 3, print "Fizz" instead of the number, and for numbers divisible by 5 (and not 3), print "Buzz" instead. When you have that working, modify your program to print "FizzBuzz", for numbers that are divisible by both 3 and 5 (and still print "Fizz" or "Buzz" for numbers divisible by only one of those). (This is actually an interview question that has be

My solution:

for(i=1; i<101; 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("What should this be?");
    }
}
like image 859
Joe Consterdine Avatar asked Dec 08 '22 20:12

Joe Consterdine


1 Answers

Your code would never reach the block inside else if (i % 3 === 0 && i % 5 === 0) because either if (i % 3 === 0) or else if (i % 5 === 0) would be true first.

Here's maybe an easier way to think about this problem:

for (var i = 1; i <= 100; i++) {
    var message = "";
    if (i % 3 === 0) {
        message = "Fizz"
    } 
    if (i % 5 === 0) {
        message += "Buzz";
    } 
    console.log(message || i);
}
like image 86
Andy Gaskell Avatar answered Dec 11 '22 09:12

Andy Gaskell