Refactored while to for loop