converting to iterative algorithm