refactored code with a loop