replaced recursion with do-while