Refactored looping logic for cleaner code.