While loop embedded in for loop refactoring