Fix loop iteration to endIndex