The if conditions could be put outside the loop.