for-loop doesn't give the expected results