Refactor from while to for