Solved fourth task using two loops