Replace some while statement to for statement