shrink the codes from two for loop to one for loop with while loop