Beginner problem - fading

Hello. I’ve started Arduino about month ago. Recently I wrote a code mingled from official tutorials with witch I have a problem.
The program is supposed to, when I press a button, fade in a LED, then light it until i press the button again and fade out. The problem is, when I press the button, LED keeps fading in from zero in circles.

const int  buttonPin = 5;
const int ledPin = 9;

int buttonPushCounter = 0;
int buttonState = 0;
int lastButtonState = 0;
int brightness = 0;
int fadeAmount = 10;

void setup() {
  pinMode(buttonPin, INPUT);
  pinMode(ledPin, OUTPUT);
  Serial.begin(9600);
}


void loop() 
{
  buttonState = digitalRead(buttonPin);

  if (buttonState != lastButtonState) {
    if (buttonState == HIGH) {
      buttonPushCounter++;
      Serial.println("on");
      Serial.print("number of button pushes:  ");
      Serial.println(buttonPushCounter);
    }
    else {
      Serial.println("off");
    }
  }
  lastButtonState = buttonState;

  if (buttonPushCounter % 2 == 0) 
  {
    for (brightness = 0; brightness <= 245; brightness = brightness + fadeAmount)
    {   
      analogWrite(ledPin, brightness);
      delay (50);
    }
    digitalWrite(ledPin, HIGH);
  } 
  if (buttonPushCounter % 2 != 0)
  {
    for (brightness = 0; brightness >= 10; brightness = brightness - fadeAmount)
    {
      analogWrite(ledPin, brightness);    
      delay(50);
    }
    digitalWrite(ledPin, LOW);
  }
}

Thanks for any help.

The two if statements at lines 34 and 43 should be a single if/else statement.

The ‘dimming’ for loop at line 45 is decrementing the brightness down from zero. IMO it would make more sense to decrement it down from 255.

The global variable brightness is only used in the two for loops and is used there as the loop control variable, so IMO it would make more sense to delete the global variable and declare it locally in each for loop:

for (int brightness = 0; brightness <= 245; brightness = brightness + fadeAmount)

By the way, it will be much easier to follow the control structure of your code if you use a consistent indenting scheme. I prefer to put each { and } on a separate line with matching pairs indented by the same amount and the lines between them indented one extra level; other people prefer to put the { on the end of the preceding line. Whichever approach you use, use it consistently. Once you have got the basic layout correct, the Tools/Autoformat command will correct the indentation for you.

Thanks for advice. It isn't only one fade, however now I have to hold the button for a second or press it when LED is on or off to change fading in/out, but it still keeps repeating the loop all over again. How to stop it?

If you only want it to do the fading when the button is pressed, then you have to put the code to do the fading in the section that is executed when the button is pressed.