Reputation: 477
I have a list of integer gotten with a for
loop. The thing i am to code 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”
But this is what i have gotten so far
function printNumber() {
for(let i = 1; i <= 100; i++) {
// document.write(i + ' ');
if(i%3 == 0) {
document.write('Fizz ');
}
else if(i%5 == 0) {
document.write('Buzz ');
}
else if(i%3 == 0 && i%5 == 0) {
document.write('FizzBuzz ');
}
else {
document.write(i + ' ');
}
}
};
But this is the result i get
1, 2, Fizz, 4, Buzz, Fizz, 7, 8, Fizz, Buzz, 11, Fizz, 13, 14, Fizz, 16, 17, Fizz, 19, Buzz, Fizz, 22, 23, Fizz, Buzz, 26, Fizz, 28, 29, Fizz, 31, 32, Fizz, 34, Buzz, Fizz, 37, 38, Fizz, Buzz, 41, Fizz, 43, 44, Fizz, 46, 47, Fizz, 49, Buzz, Fizz, 52, 53, Fizz, Buzz, 56, Fizz, 58, 59, Fizz, 61, 62, Fizz, 64, Buzz, Fizz, 67, 68, Fizz, Buzz, 71, Fizz, 73, 74, Fizz, 76, 77, Fizz, 79, Buzz, Fizz, 82, 83, Fizz, Buzz, 86, Fizz, 88, 89, Fizz, 91, 92, Fizz, 94, Buzz, Fizz, 97, 98, Fizz, Buzz,
The issue is that the numbers that are multiples of 3 and 5 don't print 'FizzBuzz'. Please can you help me with what caused this issue< Thanks in advance.
Upvotes: 0
Views: 818
Reputation: 91385
for(let i = 1; i <= 100; i++) {
if(i%3 == 0) {
document.write('Fizz');
}
if(i%5 == 0) {
document.write('Buzz');
}
if(i%3 != 0 && i%5 != 0) {
document.write(i);
}
document.write(', ');
}
Upvotes: 1
Reputation: 8589
The other solution to fizzbuzz would be to use a string that you can add the words to and then writing the output at the end of the loop.
You had an issue in your code because if i % 3 equals 0, the other checks would not be performed and hence, you never reach the check for i % 3 AND i % 5 together.
for(let i = 1; i <= 100; i++) {
let output = '';
if ( i % 3 === 0 ) output += 'Fizz';
if ( i % 5 === 0 ) output += 'Buzz';
if ( !output ) output = i;
document.write( output + ' ' );
}
Upvotes: 2
Reputation: 3021
The code will not enter to else if block if it enters if block.
when i = 15
it will enter in if(i%3 == 0)
and print 'Fizz'
and then increment i to 16 and continue..
To solve it, please check if the number is multiple of both 3 and 5 first.
Code will be
function printNumber() {
for(let i = 1; i <= 100; i++) {
// document.write(i + ' ');
if(i%3 == 0 && i%5 == 0) {
document.write('Fizz ');
}
else if(i%5 == 0) {
document.write('Buzz ');
}
else if(i%3 == 0) {
document.write('FizzBuzz ');
}
else {
document.write(i + ' ');
}
}
};
Upvotes: 1