fixed potential number overflow

first check if `i` is still within the array boundaries, then increment it. this will prevent number over flows and speed up things.