2

Is it possible for a for-loop to repeat a number 3 times? For instance,

for (i=0;i<=5;i++)

creates this: 1,2,3,4,5. I want to create a loop that does this: 1,1,1,2,2,2,3,3,3,4,4,4,5,5,5

Is that possible?

0

9 Answers 9

6
 for (i=1;i<=5;i++)
     for(j = 1;j<=3;j++)
         print i;
Sign up to request clarification or add additional context in comments.

Comments

3

Yes, just wrap your loop in another one:

for (i = 1; i <= 5; i++) {
   for (lc = 0; lc < 3; lc++) {
      print(i);
  }
}

(Your original code says you want 1-5, but you start at 0. My example starts at 1)

2 Comments

This will print 0,1,2,3,4,5,0,1,2,3,4,5,0,1,2,3,4,5.
That will print 0,1,2,3,4,5,0,1,2,3,4,5,0,1,2,3,4,5
3

You can have two variables in the for loop and increase i only when j is a multiple of 3:

for (i=1, j=0; i <= 5; i = ++j % 3 != 0 ? i : i + 1)

Comments

1

Definitely. You can nest for loops:

for (var i = 1; i < 6; ++i) {
    for(var j = 0; j < 3; ++j) {
        print(i);
    }
}

Note that the code in your question will print 0, 1, 2, 3, 4, 5, not 1, 2, 3, 4, 5. I have fixed that to match your description in my answer.

Comments

0

Just add a second loop nested in the first:

for (i = 0; i <= 5; i++)
    for (j = 0; j < 3; j++)
        // do something with i

Comments

0

You can use nested for loops

for (var i=0;i<5; i++) {
  for (var j=0; j<3; j++) {
   // output i here
  }
}

Comments

0

You can use two variables in the loop:

for (var i=1, j=0; i<6; j++, i+=j==3?1:0, j%=3) alert(i);

However, it's not so obvious by looking at the code what it does. You might be better off simply nesting a loop inside another:

for (var i=1; i<6; i++) for (var j=0; j<3; j++) alert(i);

Comments

0

I see lots of answers with nested loops (obviously the nicest and most understandable solution), and then some answers with one loop and two variables, although surprisingly nobody proposed a single loop and a single variable. So just for the exercise:

for(var i=0; i<5*3; ++i)
   print( Math.floor(i/3)+1 );

Comments

0

You could use a second variable if you really only wanted one loop, like:

for(var i = 0, j = 0; i <= 5; i = Math.floor(++j / 3)) {
     // whatever
}

Although, depending on the reason you want this, there's probably a better way.

1 Comment

I think your termination condition should test i <= 5.

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.