Substitute recursion with while-loop