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?

Vincent Ramdhanie
  • 102,349
  • 23
  • 137
  • 192
user713052
  • 25
  • 2
  • 7

9 Answers9

6
 for (i=1;i<=5;i++)
     for(j = 1;j<=3;j++)
         print i;
Vincent Ramdhanie
  • 102,349
  • 23
  • 137
  • 192
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)

yan
  • 20,644
  • 3
  • 38
  • 48
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)

weltraumpirat
  • 22,544
  • 5
  • 40
  • 54
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.

PleaseStand
  • 31,641
  • 6
  • 68
  • 95
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.

Hasanavi
  • 8,455
  • 2
  • 29
  • 35
Ry-
  • 218,210
  • 55
  • 464
  • 476
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
Andrew Cooper
  • 32,176
  • 5
  • 81
  • 116
0

You can use nested for loops

for (var i=0;i<5; i++) {
  for (var j=0; j<3; j++) {
   // output i here
  }
}
dalton
  • 3,656
  • 1
  • 25
  • 25
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);
Guffa
  • 687,336
  • 108
  • 737
  • 1,005
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 );
davin
  • 44,863
  • 9
  • 78
  • 78