refactored while into for loop