Thanks for your quick replies ,
After reading your suggestions, I managed to solve this problem by editing the condition of the while loops to include a condition to check for the array range.