[solved] for loops with multiple variables

Is there a way to have a for loop with two variables that it iterates through. I want one variable to start at 15 and go down to 0. I want the other variable to start at 39 and go down to 22.

1 Like

Simultaneously or one then the other or like each first variable increment runs all of the second ones each time or what?

for( int i = 15; i >= 0; i--)
{
  for( int j = 39; j >= 22; j--)
  {
    Serial.print("(");
    Serial.print(i);
    Serial.print(",");
    Serial.print(j);
    Serial.print("), ");
  }
}

I think you’re asking for something that behaves like this:

 void setup() {
   int i;
   int k;

  Serial.begin(9600);

  i = 15;
   for (k = 39; k > 21; k--) {
      Serial.print("i = ");
      Serial.print(i);
      if (i != 0)
        i--;
      Serial.print("   k = ");
      Serial.println(k);
   }

}

void loop() {
  // put your main code here, to run repeatedly:

}

You can do this:

    for (int i = 15, j = 39; (i > 0) && (j > 22); i++, j--)
    {
            ....
    }

Regards, Ray L.

1 Like

i don't want nested if statements.

my code is:

for(int i = 9; i > -1; i--) {
    digitalWrite(outputPin, bitRead(value, i));
    outputPin = outputPin - 1;

I was hoping for a neater solution. I am trying to do binary to decimal conversion and output it to an array of wires.

@RayLivingston

Your solution works fine. Thanks

1 Like

Couldn't you just type dec before the binary value instead of converting yourself? I thought the Arduino knows the diff formats of the same value.

135843:
I want one variable to start at 15 and go down to 0.

a total of 16 iterations

135843:
I want the other variable to start at 39 and go down to 22.

a total of 18 iterations.

How many times did you want the code in the loop to execute?