replace for loop with while loop