How to toggle LED on button press?
At the moment, you've got two main problems. Firstly, both your if statements are being triggered one after the other. This is because the first if statement sets x to 0, which is part of the condition the second if statement looks for.

The second problem is that you're not monitoring the previous state of the button. buttonState will appear HIGH every time round loop, even if the button has been held down for several seconds. The result is that the output pin will be quickly getting turned on and off all the time.

What you need to do is store the last known state of the button. On every iteration of the main loop, only respond to the button if it's currently HIGH, and if it was LOW last time round the loop. You also need to make sure your two if statements are mutually exclusive; i.e. if you trigger one then don't trigger the other by mistake too, or it will cancel it out.

Something like this should work better:

// This will store the last known state of the button
int oldButtonState = LOW;

void loop()
{
  // Get the current state of the button
  int newButtonState = digitalRead(buttonPin);

  // Has the button gone high since we last read it?
  if (newButtonState == HIGH &amp;&amp; oldButtonState == LOW) {

    if (x == 0) {
      // Toggle on
      digitalWrite(ledPin, HIGH);
      x = 1;

    } else {
      // Toggle off
      digitalWrite(ledPin, LOW);
      x = 0;
    }
  }

  // Store the button's state so we can tell if it's changed next time round
  oldButtonState = newButtonState;
}


As noted elsewhere, you still need to debounce the button, otherwise you're likely to get some false-positives. That can be done in hardware or software. A really simple way to get around it temporarily is to put in a delay of several milliseconds every time you detect the button changing state. It's not perfect, but it might be enough to get you started.