replace while by for loop where appropriate