refactored code using a for loop to iterate through names array