Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

print numbers between 1- 20 using rules

Tags:

javascript

I am going through codeacademys JavaScript tutorials as i am new to it. The tutorial asks for the following:

Print out the numbers from 1 - 20.
The rules:
- For numbers divisible by 3, print out "Fizz".
- For numbers divisible by 5, print out "Buzz".
- For numbers divisible by both 3 and 5, print out "FizzBuzz" in the console.
- Otherwise, just print out the number.

Here is my code:

for (i=1; i<=20; i++) {

if(i%3==0) {
    console.log("Fizz");
} 
if(i%5==0){
    console.log("Buzz");
}else if (i%5==0 && i%3==0) {
    console.log("fizzBuzz");
} else {
    console.log(i);
}

}

i am getting an error saying that i am printing out the wrong number of items, anyone know why that is?


1 Answers

The check for both 3 and 5 must be first, otherwise the two other statements are true already and give separate logs. Now you print FizzBuzz in a single console.log statement.

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

    }
like image 196
Ferdinand Torggler Avatar answered Jul 13 '26 22:07

Ferdinand Torggler