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:
You should check if a number is divisible by both 3 and 5 in your first IF, since numbers that are divisible by both would otherwise result in the first and the second IF statement being executed.
Furthermore, the rules tell you to write out "FizzBuzz" in case a number is divisible by both, and at the moment you're only printing out "Buzz".
Here is I got the answer correct.
for(var i=1;i<=20;i++)
{
if(i%3 === 0 && i%5 === 0)
{
console.log("FizzBuzz");
}
else if(i%3 === 0)
{
console.log("Fizz");
}
else if(i%5 === 0)
{
console.log("Buzz");
}
else
{
console.log(i);
}
}
The result will be:
1 2 Fizz 4 Buzz Fizz 7 8 Fizz Buzz 11 Fizz 13 14 FizzBuzz 16 17 Fizz 19 Buzz
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);
}
}
var i=1;
while (i<21)
{
if(i%3!==0 && i%5!==0)
{
console.log(i);
}
if(i%3===0 && i%5===0 )
{
console.log("FizzBuzz");
}
else if(i%3===0)
{
console.log("Fizz");
}
else if(i%5===0)
{
console.log("Buzz");
}
i++;
}
for (var i=1 ; i<=20 ; i++){
if (i%3===0 && i%5!=0){
console.log("Fizz");
} else if (i%5===0 && i%3!=0){
console.log("Buzz");
} else if (i % 3 === 0 && i % 5 === 0 ){
console.log("FizzBuzz");
} else {
console.log (i);
}
}
I don't know Javascript, but I know some Python and I've come across the same problem. Maybe this can help. I'm sure someone can just translate this for Javascript.
Here's the original problem: Loop through the numbers between 1 and 20. If a number is divisible by 3, print Hip. If the number is divisible by 7, print “Hooray”.
Here's the code for python for a similar problem:
for numbers in range(1,21):
if numbers % 3 !=0 and numbers % 7 != 0:
print(numbers)
if numbers % 3 == 0:
print("Hip")
if numbers % 7 == 0:
print("Hooray")
Here's the output:
1 2 Hip 4 5 Hip Hooray 8 Hip 10 11 Hip 13 Hooray Hip 16 17 Hip 19 20