HELP! LED Fading with Switch

hello guys, i'm just getting started with the arduino and i'm trying to make a arduino to control fade in and out a led with the switch.
i use the arduino digital input pin 2 as my input switch and pwm out from pin 9.i want to do is when i turn on the switch ( input HIGH) led will gradually turn on and stay on until i turn off the switch and when i turn off led will gradually turn off. i manage to make the led fade in when i turn on the button but its not stays on after when it fade in. can any one point me whats the problem.

int ledPin = 9;

void setup()
{
  pinMode( 2, INPUT);
}

void loop()
{ int fadeValue;

  if (( ( digitalRead(2) ) == ( HIGH ) ))
  {
    for (fadeValue = 0 ; fadeValue < 255; fadeValue++)
    {
    analogWrite(ledPin, fadeValue);
    delay(10);
  }
  }
  else
  {
    analogWrite(ledPin, 0 );
  }
}

The behaviour of your code is that as long as the switch is on, the LED will fade from 0 to 255 over and over again.
At the moment that you switch the switch off, the LED will be off.

I guess you want to fade from 0 to 255 only once and stay on 255 afterwards as long as the switch is on

void loop()
{
  static int fadeValue = 0;

  // if switch is ON
  if (digitalRead(2) == HIGH)
  {
    // if not at maximum
    if (fadeValue < 255)
    {
      // increment intensity
      fadeValue++;
      // write LED intensity
      analogWrite(ledPin, fadeValue);
      // wait a little
      delay(10);
    }
  }
  // if switch is OFF
  else
  {
    // switch LED off
    analogWrite(ledPin, 0 );
    // reset fade value to reflect the intensity of the LED
    fadeValue = 0;
  }
}

Remember that loop is executed permanently; so the above will increment fadevalue every iteration of the loop() (instead if in a for-loop).

Using a static variable prevents the last value from being forgotten.

Not tested.

thank you. its working.but i also want the led to fade off when i release the button. can you please explain how to do that.

In the else, decrement fadeValue (use 'fadeValue--') and use that value for the analogWrite. Do not forget to stop when fadeValue reaches 0.

yes i figure it out. please tell me if this code has any errors

int ledPin = 9;
void setup()
 {
  pinMode( 2, INPUT);
 }
void loop()
 {
static int fadeValue = 0;
 if (digitalRead(2) == HIGH)
  {
   if (fadeValue < 255)
   {
    fadeValue++;
     analogWrite(ledPin, fadeValue);
     delay(10);
   }
  }
 else
 {
  if (fadeValue > 0)
   { fadeValue--;
    analogWrite(ledPin, fadeValue);
    delay(10);
   }
  }
 }

Looks OK; did you test it?

yes its working without problem.