Reputation: 25
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?
Upvotes: 2
Views: 5688
Reputation: 224906
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.
Upvotes: 0
Reputation: 45525
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 );
Upvotes: 0
Reputation: 700252
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);
Upvotes: 0
Reputation: 32062
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.
Upvotes: 1
Reputation: 22604
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)
Upvotes: 3
Reputation: 3696
You can use nested for loops
for (var i=0;i<5; i++) {
for (var j=0; j<3; j++) {
// output i here
}
}
Upvotes: 0
Reputation: 32576
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
Upvotes: 0
Reputation: 20982
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)
Upvotes: 3