refactored with for loops