Rewrite using for loops