# how to combine 2 for loops?

Hi,

I have two loops. if i run this piece of code, the first loop will do his job first, then the second one.
But it’s not wat i want, i want the loops are combined, so both actions wil perform “at the same time”.
I’ve tried this but that doesn’t work. Can anyone help? Thanks in advance.

for (int i = 8; i > -1; i--) {
setPixel(i,7,0,1,0,0);
delay(TD10);
}

for (int k = 0; k < 8; k++) {
setPixel(7,7,k,1,0,0);
delay(TD10);
}
for (int i = 8; i > -1; i-- && int k = 0; k < 8; k++) {
setPixel(i,7,0,1,0,0);
setPixel(7,7,k,1,0,0);
delay(TD10);
}

you have multiple challenge

the first one is that your proposed code does not respect the structure of a for statement

for ( declaration-or-expression(optional) ; declaration-or-expression(optional) ; expression(optional) ) statement

you don't have the right elements in the right place.

your second issue is that the first loop loops 9 times and the second one only 8. so grouping them is a bit trickier that what it appears...

can u give an example? I doens't matter how the code is written, it just needs to work

for (int i = 8; i > -1; i--) {

9 iterations

for (int k = 0; k < 8; k++) {

8 iterations

is that right ?

If the number of iterations in each loop is the same than you can do something like

for (int x = 7;x >= 0; x--)
{
setPixel(x,7,0,1,0,0);  //7 to 0
setPixel(7,7,7 - x,1,0,0);  //0 to 7
delay(TD10);
}

if you don’t want to do maths with indexes, here is an example of a for loop with 2 indexes but with same number of steps

void setup() {
Serial.begin(115200);
for (int i = 0, k = 7; (i < 8) && (k >= 0); i++, k--) {
Serial.print("i = "); Serial.print(i);
Serial.print(" and k = "); Serial.println(k);
}
}

void loop() {}

Why have you not replied to my earlier comments on shortening your code, in another almost identical thread.?

well, i think the previous post was in the wrong section. In this section i got an quicker answer. In the previous post the question was not totally clear.

In this section i got an quicker answer.

And in the origin post you did not use code tags. That puts a lot of people off answering a question because they think if he can't be arsed to read how to use this forum, I can't be arsed answering them.