Go Down

Topic: [solved] for loops with multiple variables (Read 6357 times) previous topic - next topic

135843

Jul 31, 2016, 03:36 am Last Edit: Jul 31, 2016, 05:25 am by 135843
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.

INTP

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

Koepel

Code: [Select]

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("), ");
  }
}

econjack

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

Code: [Select]

 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:

}

RayLivingston

You can do this:

Code: [Select]

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


Regards,
Ray L.

135843

i don't want nested if statements.

my code is:
Code: [Select]
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.

135843

@RayLivingston

Your solution works fine. Thanks

INTP

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.

PaulMurrayCbr

I want one variable to start at 15 and go down to 0.
a total of 16 iterations

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?
http://paulmurraycbr.github.io/ArduinoTheOOWay.html

Go Up