Implemented the loop code from the book