Seperated the if condition to outside the loop