Use one while loop instead of two for loop