Problem: Define a function fizzBuzz(max) that takes a number and prints every number from 0 to max (not inclusive) that is divisible by 3.
Hi all,
For the above question, I’m not sure why I use while loop as below it doesn’t work but I need to add another if conditional statement.
Does not work
let i=0;
while (i<max && i%3===0) {
console.log (i);
i++;
}
Work
let i=0;
while (i<max) {
if (i%3===0) {
console.log (i);
}
i++;
}
Thank you very much for your response.
2
Answers
The two snippets you provided aren’t equivalent. Once the condition of the
while
loop isn’t met, the loop terminates. So, in the first snippet, after printing out0
, the loop’s condition evaluates1
, finds the condition to befalse
(since1%3
is1
, not0
), and terminates the loop. In the second snippet, the loop continues iterating untili
is equal tomax
, and theif
condition inside it is in charge of determining whetheri
needs to be printed or not.Side note #1:
Since you know
0
is divisible by3
, you could increment in steps of3
to just get all the numbers divisible by3
instead of checking all the numbers in between:Side note #2:
This is probably a matter of style, but since the body of the only effect the body of the loop has on the condition is a fixed increment of
i
, afor
loop feels more appropriate, at least to me:Your loop doesn’t work because it breaks when
i === 1
since1%3 !== 0
andi<max && i%3===0
isfalse
.Your second code snippet solves that problem.
There’s also an option to use a functional one-liner and generate a fake array and print its indices multiplied by
3
: