I'm not sure it is productive to worry about optimizations at this level. Generally it is more important to get the program working and move on to the next problem.
Having said that, there is an optimization called loop unswitching that some compilers will do for you. They duplicate the loop, once with and once without the conditional, and move the conditional outward to select the loop. (In your example you could make the entire loop conditional but I presume that's just an artifact of simplification for Stack Overflow.)
But this is just one more reason not to worry too much about optimizations, at least, not until you have a profile and you know that this region of code is responsible for detectable amounts of runtime.
Still, it's best to write code as cleanly as you can and puzzling through issues like this will teach you good things...
In fact, loop-invariant conditionals bother me too. I don't believe there is a general answer. There are fancy answers involving higher order functions or lambdas, "leave-it-to-the-compiler" answers, refactor-the-whole-outer-routine answers ... I would generally approve of whatever makes the code appear smaller. You have to prioritize in order to discriminate...