Literal re-write the “stoplight” sketch using arrays

The example below shows how to re-write the stoplight sketch given
in the example using arrays. Note that no program optimization
has been done (yet); instead, the substitution of array elements is just
done literally:

/* Use arrays rather than individual variables for LED pins and delay times.  
   Note that this program is not shorter than the original example, and is in 
   fact less readable. */

#define REDLED       4       // the red LED will be connected to Digital Pin 4
#define GREENLED     5 
#define YELLOWLED    6 
#define REDTIME      10000   // 10 seconds for the red light
#define GREENTIME    6000    //  6 seconds for the green light
#define YELLOWTIME   4000    //  4 seconds for the yellow light

const int leds[] = { REDLED, GREENLED, YELLOWLED };
int delays[]     = { REDTIME, GREENTIME, YELLOWTIME };

void setup() {
  pinMode(leds[0], OUTPUT);
  pinMode(leds[1], OUTPUT);
  pinMode(leds[2], OUTPUT);
  digitalWrite(leds[0], LOW);
  digitalWrite(leds[1], LOW);
  digitalWrite(leds[2], LOW);
}

void loop() {
  digitalWrite(leds[0], HIGH);
  delay(delays[0]);
  digitalWrite(leds[0], LOW);
  digitalWrite(leds[1], HIGH);
  delay(delays[1]);
  digitalWrite(leds[1], LOW);
  digitalWrite(leds[2], HIGH);
  delay(leds[2]);
  digitalWrite(leds[2], LOW);
}

Wait! This is no shorter than, and actually less readable than the original code!

Re-write using loops

Now re-write the above sketch using for loops:

int pins[] = { 4,5,6 };
unsigned int delays[] = { 10000, 6000, 4000 };

void setup() {
  for (int i = 0; i < 3; i++) {
      pinMode(pin[i], OUTPUT);
      digitalWrite(pin[i], LOW);
  }
}

void loop() {
  for (int i = 0; i < 3; i++) {
    digitalWrite(pin[i], HIGH);
delay(delays[i], LOW);
  }
}

Not only is the code much shorter, but it would not need changing at all if you
happened to be using arrays that were much, much larger.