use recursion instead of while loop