code from Alogrithms section 1.2