shorten arduino code when useing multiple led and buttons

hello, i¨m quite new to this arduino and microcontrollers but i love it more and more.

i¨m currently just playing with mulitple buttons 2-10 controlling multiple leds 1-10 and i wonder if there is any way to [u]shorten the code or simplify it?[/u] even more? i feel there is many line of text that is almost the the same the difference is only 1 or 2 numbers...

int redPin = 11;
int greenPin = 10;
int bluePin = 9;

int button2State = 0;
int button4State = 0;
int button7State = 0;

const int button2Pin = 2;
const int button4Pin = 4;
const int button7Pin = 7;

void setup(){
  pinMode(button2Pin, INPUT);
  pinMode(button4Pin, INPUT);
  pinMode(button7Pin, INPUT);

  pinMode(redPin, OUTPUT);
  pinMode(greenPin, OUTPUT);
  pinMode(bluePin, OUTPUT);
}

void loop()
{
button2State = digitalRead(button2Pin);
button4State = digitalRead(button4Pin);
button7State = digitalRead(button7Pin);

if (button2State == HIGH) {
  digitalWrite(redPin, HIGH);
  } else {
    digitalWrite(redPin, LOW);
}
if (button4State == HIGH) {
  digitalWrite(bluePin, HIGH);
  } else {
    digitalWrite(bluePin, LOW);
}
if (button7State == HIGH) {
  digitalWrite(greenPin, HIGH);
  } else {
    digitalWrite(greenPin, LOW);
}
}

i feel there is many line of text that is almost the the same the difference is only 1 or 2 numbers…

That’s when you want to use arrays

// before setup
byte x;
byte inArray[] = {0,1,2,3,4,5,6,7,8,9,}; // 0, 1 not available for serial debug - but the code is pretty simple
byte outArray[] = {10,11,12,13,14,15,16,17,18,19,};
void setup(){
for (x=0; x<10; x=x+1){
pinMode (outArray[x]], OUTPUT);
pinMode (inArray[x], INPUT_PULLUP);
}
}
void loop () {
for (x=0; x<10; x=x+1){
  if (digitalRead (inArray[x]) == 0){
  digitalWrite (outArray[x], HIGH);
  }
  else {
(digitalWrite (outArray[x], LOW);
  }
}
} // check, make sure these are all paired up

Is that too short for you?

CrossRoads: That's when you want to use arrays

Perhaps, but you have lost the naming there, which is part of the self-explanatory, minimally commented code.

It may be rather more legible to use a function.

int redPin = 11;
int greenPin = 10;
int bluePin = 9;

int button2State = 0;
int button4State = 0;
int button7State = 0;

const int button2Pin = 2;
const int button4Pin = 4;
const int button7Pin = 7;

void setup() {
  pinMode(button2Pin, INPUT);
  pinMode(button4Pin, INPUT);
  pinMode(button7Pin, INPUT);

  pinMode(redPin, OUTPUT);
  pinMode(greenPin, OUTPUT);
  pinMode(bluePin, OUTPUT);
}

void relay(int butnPin, int state, int ledPin) {
  state = digitalRead(butnPin);
  if (state == HIGH) {
    digitalWrite(ledPin, HIGH);
  } else {
    digitalWrite(ledPin, LOW);
  }
}

void loop()
{
  relay(button2Pin, button2State, redPin);
  relay(button4Pin, button4State, bluePin);
  relay(button7Pin, button7State, greenPin);
  delay(20);
}