Changing recursive function to use iterative loop