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?
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)
0,1,2,3,4,5,0,1,2,3,4,5,0,1,2,3,4,5I 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 );
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.
i <= 5.