refactored code to use loops