refactored using for and for-each loops