convert tail recursive function to while loop

convert tail recursive function to while loop
fix a bug in convert recursive function by using temp parameters.