refactored loops in task 2,3