changed spaghetti code to 'for' cycle