It seems like the n=n+1
is inside the for
loop, which may be causing it to increment multiple times unexpectedly. You might be skipping some indexes or going out of range. Try moving the increment outside the for
loop or consider using a nested loop instead of combining while
and for
.