Fizzbuzz test in Javascript

Asked

Viewed 2,431 times

1

I am trying to take the test "FIZZBUZZ" which consists of the following:

Write a program that prints the Numbers from 1 to 100. But for multiples of three print "Fizz" Instead of the number and for the multiples of five print "Buzz". For Numbers which are multiples of Both three and five print "Fizzbuzz".

I wrote the following code, but it is not working! Someone can give me a light?

var n = 1;

while (n <= 100) {
    if ((n % 3) == 0 || (n % 5) == 0) {
        if ((n % 3) == 0 && (n % 5) == 0) {
            console.log("FizzBuzz");
        }
        else if (n % 3 == 0 && (n % 5) !== 0) {
            console.log("Fizz");
        }
        else if ((n % 5) == 0 && (n % 3) !== 0) {
            console.log("Buzz");
        }
    else {
        console.log(n);
    }
    }
n = n + 1;
}

If you have suggestions on how to make my code clearer, you are most welcome!

  • Which part doesn’t work?

  • When I run the code and see in the Chrome console the numbers don’t appear!

  • Only appears Fizz, buzz or fizzbuzz you not printing the numbers.

3 answers

3


Numbers that are not multiples of 3 or 5 are not printed because they are inside the first if and there is no console.log for them.

if ((n % 3) == 0 || (n % 5) == 0) {

    } else {
       console.log(n);
    } <-- os demais números depois dessa linha, que não tem nenhum console.log
    n = n + 1;
} 

Suggestion:

var n = 1;

while (n <= 100) {
    if(n % 3 == 0 && n % 5 == 0){
        console.log(n +" FizzBuzz");
    }else if(n % 5 == 0){
        console.log(n +" Buzz");
    }else if(n % 3 == 0){
        console.log(n +" Fizz");
    }
    n++;
}
  • Thank you so much for your help! Hug!

1

Suggestion would he make with the for:

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

1

I was able to find the problem of my code! Everything was a } in the wrong place! To be documented, the functional code looks like this:

var n = 1;

while (n <= 100) {
    if ((n % 3) == 0 || (n % 5) == 0) {
        if ((n % 3) == 0 && (n % 5) == 0) {
            console.log("FizzBuzz");
        }
        else if (n % 3 == 0 && (n % 5) !== 0) {
            console.log("Fizz");
        }
        else if ((n % 5) == 0 && (n % 3) !== 0) {
            console.log("Buzz");
        }
    }
    else {
        console.log(n);
    }
n = n + 1;
}

It is not the most elegant solution. However, it solves the problem! Hug to all!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.