0

Is there something wrong with my code?

I tried to make a JS program that was supposed to output all the numbers from 1 to 100 but all the numbers dividable by 3 was supposed to output "Fizz" and every number dividable by 5 should say "Buzz. Here it is: for(var i = 0; i <= 100; i++) { if(i%=3==0) { document.write("Fizz \n"); } else if(i%=5==0) { document.write("Buzz \n"); } else { document.write(i+"\n"); } } Can you help me?

27th Feb 2017, 10:30 PM
Daniel
Daniel - avatar
6 Réponses
+ 3
You don't test all your cases: You need to test if dividable by 3 and by 5... but also if dividable by 3 and 5: actually, in this case, you output "Fizz" but not "Buzz" for multiplier of 15 ( 3*5 )... Add a test at start of your if-else chain to fix that... And you must not use the %= operator in your test condition, as it's an assignement operator, so value of i was changed ( you don't compare the good value on next comparisons, in addtion to do an infinite loop -- i was always lighter than 3 ): for(var i = 0; i <= 100; i++) { if(i%3==0)&&(i%5==0) { document.write("Fizz'n'Buzz<br>"); } else if(i%3==0) { document.write("Fizz<br>"); } else if(i%5==0) { document.write("Buzz<br>"); } else { document.write(i+"<br>"); } } I've changed you '\n' by '<br>', as usually you are output in Html document ( so default behavior is to ignore break-lines chars )...
1st Mar 2017, 4:50 AM
visph
visph - avatar
0
if(i%=5==0)
27th Feb 2017, 10:32 PM
Mohamed Fawzy
Mohamed Fawzy - avatar
0
that doesnt change anything, "else if" allows you to add another comparison just like an "if" statement does
27th Feb 2017, 10:37 PM
Daniel
Daniel - avatar
0
i mean u need to delete the = operator before the 5
27th Feb 2017, 10:41 PM
Mohamed Fawzy
Mohamed Fawzy - avatar
0
ohh.. haha thank you
27th Feb 2017, 10:42 PM
Daniel
Daniel - avatar
0
u r welcome :)
27th Feb 2017, 10:43 PM
Mohamed Fawzy
Mohamed Fawzy - avatar