Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

JavaScript

While Statements

Got stuck on this While statement algorithm. Thank you!:

Multiples of Six Print multiples of 6 up to 60,000, using a WHILE.

function integers() {
    var i = 1;
    while (i <= 60000) {
      document.write(i + " </br>");
        i++;
      if ((i % 6) === 0) {
      document.write(i + " </br>");
        i++;
    }
  }
}
integers()
Steven Parker
Steven Parker
242,796 Points

Please provide a link to the course page to allow for a complete and accurate analysis.

3 Answers

You are printing twice. Your first document write is printing every time i is less than 60,000. You're also trying to increment i twice, and once inside an if statement which would mean it only increments if i % 6 === 0. You want to increment i during each iteration. Here is how your function should look if you want to print multiples of 6 between i and 60,000 using a while loop.

function integers() {
  var i = 1;
  while (i <= 60000) {
    if ((i % 6) === 0) {
      document.write(i + " </br>");
    }
    i++;
  }
}

integers()

Before I saw your best answer I tried to solve it myself and came out with this code. It seems to run identical to the code you wrote. I just kept the i++ inside the while statement. Is this wrong? Anyways, thanks for helping. I been doing algorithms as extra practice.

var i = 0;

function multiplesOfSix() {
  while (i <= 60000) {
    i++;
    if ((i % 6) === 0) {
      document.write(i + " </br>");
    }
  }
}
multiplesOfSix()
Steven Parker
Steven Parker
242,796 Points

By incrementing first, instead of having a range of 0 to 60000, you would have a range of 1 to 60001. But in this case, since you only print multiples of 6, you might not see any difference.

My i++ is in the while statement, it's just after the if statement. You should really be incrementing i after your if statement, because placing it before the if statement means i increments before your condition, excluding the first instance of i from the condition. Other than that, it's great!

OK, got it! This is just a practice algorithm Steve. It's not from Tree House. Just trying to learn more. Thanks!