bizarre program fault

Im trying to write a sketch in which I use an LDR and an LED. What Im trying to accomplish is when the LED turns on in front of the LDR, the variable s1 stores the time it happens and when the LED turns off s2 stores that time. The program doesnt work when run as it is but when I use the Serial.print() section at the bottom or use a delay, the program runs properly. I dont understand the reason ...plz someone help me.

here is the sketch:

const int sense=1;
int scan, oldscan, permit1, permit2;
unsigned long s1, s2;

void setup()
{
 Serial.begin(9600);
 oldscan = analogRead(sense);
}

void loop()
{
  scan = analogRead(sense);

 if(scan - oldscan > 300  &&  permit1 == 0)
 {
   s1 = millis();
   permit1 = 1;
   permit2 = 0;
   Serial.print("s1=");
   Serial.println(s1); 
 }

 if(oldscan - scan > 300  &&  permit2 == 0)
 {
   s2 = millis();
   permit2 = 1;
   permit1 = 0;
   Serial.print("s2=");
   Serial.println(s2); 
 }

 oldscan = scan;

// delay(500);

/*  Serial.print("scan=");
 Serial.println(scan);
 Serial.print("oldscan=");
 Serial.println(oldscan);
 Serial.print("permit1=");
 Serial.println(permit1);
 Serial.print("permit2=");
 Serial.println(permit2);        */
 
}

The program doesnt work when run as it is

You have not said what does it do ?

LDRs have slow response, so here I've added a minimum interval (20ms) between input cycles. This will also allow more time for printing to complete for faster or noisy signals. Also used "unsigned" where possible (untested).

const int sense = 1;
unsigned short scan, oldscan, interval = 20;

unsigned long s1, s2, previous;

void setup()
{
  Serial.begin(9600);
  oldscan = analogRead(sense);
}

void loop()
{
  unsigned long now = millis();
  scan = analogRead(sense);

  if (now - previous >= interval)
  {
    if (scan - oldscan > 300 )
    {
      s1 = millis();
      Serial.print("s1=");
      Serial.println(s1);
    }
    else if (oldscan - scan > 300)
    {
      s2 = millis();
      Serial.print("s2=");
      Serial.println(s2);
      previous = now;
    }
  }
  oldscan = scan;  
}

@sorkora

Please edit your post, select the code, and put it between [code] ... [/code] tags.

You can do that by hitting the "Code" button above the posting area (It looks like a scroll with < > inside it).