Data being lost after serial

I wrote this code, so that the data that is sent via serial can be displayed on a 16x2 screen. The reason for creating my own scrolling function is that using autoscroll I was not able to use more than 24 characters in one line.
But the issue is that the string that I send is first stored correctly but then while displaying at some point it loses the first character that the user sends. I tried plugging in some random character by default in the STR[0] but even then only the data sent by the user is lost.

#include<SPI.h>
#include<LiquidCrystal.h>

LiquidCrystal lcd(2,3,4,5,6,7);
char STR[40];


void setup()
{
  lcd.begin(16,2);
  Serial.begin(9600);
  lcd.setCursor(0,0);
  lcd.write("WELCOME");
}

void loop()
{

  if(Serial.available())
  {
    int i=0;                  //i variable is for counting the string length 
    while(Serial.available()>0)
    {
      STR[i]=Serial.read();
      i++;
    }
    Serial.println(STR[0]);   //Here the output for STR[0] is the first character of the string.
    char a=STR[0];            //Here the output for a is the first character of the string
    Serial.println(a);
    for(int z=0;z<3;z++)
      {
       lcd.clear();
       int j=0, k=0;          //j decides the number of character that is to be displayed, k helps to select the frame of characters to be displayed on the screen
       while(j<16&&j<i)
       {
         for(int n=0;n<=j;n++) 
          {
            lcd.setCursor(15-j+n,1);
            lcd.write(STR[n]);
            Serial.print(STR[n]);
          }
         j++;
         delay(400);
       }
       while(j>=16&&j<=i)
       {
         lcd.clear();
         for(int n=k;n<k+16;n++) 
          {
            lcd.setCursor(n-k,1);
            lcd.write(STR[n]);
           }
         k++;
         j++;
         delay(400);
       }  
      }
  Serial.println(STR[0]);     //Here the output for STR[0] is actually the second character of the string
  Serial.println(a);          //Here the output for a is actually the second character of the string
  }
}

Put the code in CODE tags so we don't lose the [ i ] and have to read italics.


Rob

while(j<16&&j<i)

Isyourspacekeybroken? If so, get it fixed. If not, make use of it!