refactored by abstracting repeating elements using for loops