Help in serial communication

Aim : send "hello" to Arduino. Arduino sends back "hi" if "hello" is received, else it sends "write hello"...via serial comm.

int x = 0;
char buffer[5];
char reply1[] = "hi";
char reply2[] = "write hello";
int i = 0;

void setup()
{
Serial.begin(9600);
}

void loop()
{
if (Serial.available() > 0&&i<5)
{
buffer[i]=Serial.read();
i++;
}

if(i==5)
{
if(buffer[0]=='h'&&buffer[1]=='e'&&buffer[2]=='l'&&buffer[3]=='l'&&buffer[4]=='o')
{
Serial.write(reply1);
i=0;
}
else
{
Serial.write(reply2);
for (int x=0; x<5; x++) 
{
buffer[x]='\0';
}
Serial.flush();
i=0;
}
}
}

This code works when i type hello in serial monitor window...but for other strings, it doesn't work.
I know the logic in the code is wrong somewhere...but can't figure it out. :frowning:
Please HELP!!

Moderator edit: code tags.

Hi,
I checked your code by uploading it into my Arduino and the code seems to work pretty well. Can you describe your problem in detail; as simply saying "it doesn't work" explains noting about the problem.
I think limiting the length of your 'buffer' array may be a part of the problem that you are facing. Also, try to replace

if (Serial.available() > 0&&i<5)
{
    buffer[i]=Serial.read();
    i++;
}

with a loop.

Hey Abhik!
Thanks,
You're right. I tried increasing the length of the buffer. I also added a longer pause to let the buffer fill completely. It worked!