First ever project - conditional statement

Hi!

I just started off with my first Arduino Sketch which, based on the voltage on 1 input pin, regulates 3 output pins connected to LEDs.

The program works just fine and includes a pushbutton which I use to decide the value of the input pin; when I click it the LEDs light up and when I do not press the button no light appears (rightfully so).

What confuses me however is why, once I press the button, the LEDs that are supposed to be on only when the button is pressed keep on being light up forever even if I disconnect the button from the breadboard or even when I disconnect the cable connecting the input pin to the breadboard.

How is it possible that although no voltage is present in the input, the output is still the same as if there was voltage in the input?

Thank you very much!

int switchState = 0;

void setup() {

pinMode(3, OUTPUT);
pinMode(4, OUTPUT);
pinMode(5, OUTPUT);
pinMode(2, INPUT);

}

void loop() {

switchState = digitalRead(2);

if (switchState == LOW) {

  digitalWrite(3, LOW); // green LED
  digitalWrite(4, LOW); // red LED
  digitalWrite(5, LOW); // red LED

  
}

else {

  digitalWrite(3, HIGH); // green LED
  digitalWrite(4, HIGH); // red LED
  digitalWrite(5, HIGH); // red LED

 
}
}

P.S. I know I am not supposed to disconnect parts of the circuit while running but since I am starting out I am trying to learn by disconnecting and connecting components and seeing what happens.

The concept you need to know about is pins which are floating. An input pin that has nothing connected to it has no guaranteed value, it can float about from high to low more or less at random.

That's why buttons always use pullup or pulldown resistors connected to the input pin so there is a defined value. With Arduino we most often use pinMode(pin, INPUT_PULLUP) with the button arranged to connect to GND when pushed. That saves you from needing an external pullup resistor.

Steve

Your code doesn't even need a condition...
(Though some pin names wouldn't go amiss)

No voltage is present in the input

To add to what slipstick said; there is always a voltage present at the input. Everything in the entire Universe made of normal matter has a voltage, including the pin you mention when it is not connected to anything. It is not a case of there not being a voltage present, it is a case of the voltage not being what you think it is or not being very well defined.