Well, how about adding some debug messages to your program to see what the problem is?
I would advice you to print the variable i, the char at i and the length of chararr in every iteration of the...