O. Brainwave O. Brainwave - 1 month ago 20
Javascript Question

Exercise on javascript

please I'm stuck in this question below since yesterday. Below is the question:


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).


I only got the first two conditions but not the the third. I don't know how to go about it anymore, I've tried many options. Below is my code:

<html>
<head/head>
<body>
<script type="text/javascript">
for (i = 1; i <= 100; i++)
if (i % 3 == 0) {
document.write("Fizz");
document.write("<br />");
} else if (i % 5 == 0 && i % 3 != 0) {
document.write("Buzz");
document.write("<br />");
} else if (i % 3 && 5 == 0 && i % 3 != 0 && i % 5 != 0) {
document.write("FizzBuzz");
document.write("<br />");
} else {
document.write(+i);
document.write("<br />");
}
</script>
</body>
</html>

Answer

Check the most specific (FizzBuzz) condition first.

function fizzBuzz() {
    for(var i = 1; i <= 100; i++){
        if(i % 5 === 0 && i % 3 === 0){
            console.log('FizzBuzz');
        } else if(i % 3 === 0){
            console.log('Fizz');
        } else if(i % 5 === 0){
            console.log('Buzz');
        } else {
            console.log(i);
        }
    }
}
Comments