skip to Main Content

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


  1. 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 out 0, the loop’s condition evaluates 1, finds the condition to be false (since 1%3 is 1, not 0), and terminates the loop. In the second snippet, the loop continues iterating until i is equal to max, and the if condition inside it is in charge of determining whether i needs to be printed or not.

    Side note #1:
    Since you know 0 is divisible by 3, you could increment in steps of 3 to just get all the numbers divisible by 3 instead of checking all the numbers in between:

    let i = 0;
    while (i < max) {
        console.log (i);
        i += 3;
    }
    

    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, a for loop feels more appropriate, at least to me:

    for (let i = 0; i < max; i += 3) {
        console.log(i);
    }
    
    Login or Signup to reply.
  2. Your loop doesn’t work because it breaks when i === 1 since 1%3 !== 0 and i<max && i%3===0 is false.

    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:

    const max = 40;
    
    Array.from({length: Math.ceil(max / 3)}, (_, i) => console.log(i * 3));
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search