0

How to alter this loop, so that it runs for i = 12, 18, 24, 30 and 36 only?

for (var i = 12; i < 36; i++) {
   console.log(i);
}

4 Answers 4

9
for (var i = 12; i <= 36; i += 6) {

   console.log(i);

} 
Sign up to request clarification or add additional context in comments.

Comments

3

The i++ in the for statement is what to do before the next iteration of the loop. So in the case of i++ we're incrementing the variable i by one. So if you want to increment by six then you need to add 6 to the variable which will give you:

for (var i = 12; i < 36; i += 6) {
    console.log(i);
} 

Next up, you want to include 36, so you need to change your condition (the bit of your loop that says i < 36) to include 36. This is really easy, you just need to change the "less than" to "less than or equal to" :

for (var i = 12; i <= 36; i += 6) {
    console.log(i);
} 

1 Comment

@NewUser: Your inner for loop has i <=20 as condition, but you are not increasing i in that inner loop. The inner loop will run forever which means the outer loop cannot increase i to terminate the inner loop.
1

Instead of doing i++ in your loop, do i += 6. Like this:

for (var i = 12; i < 36; i += 6) {
    console.log(i);
}

1 Comment

That will stop before printing 36.
1

Alternatively (though not necessarily better):

for(var i, values = [12, 18, 24, 30, 36]; i = values.shift();) {
    console.log(i);
}

This shows that you do not need to have an increasing counter in a for loop.

1 Comment

Interesting. For more complicated examples (without a pattern) could be useful.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.