They produce different outputs because the inner loops are, in no way, equivalent.
The test i != j
does not affect the number of iterations on the inner loop in the first form - the number of iterations will always be 5
, and the if (i != j) ...
will be executed on every loop iteration.
However, in the second lot of code, i != j
is now part of the loop condition, so the loop will terminate after five iterations OR the first time it finds i != j
is false (i.e. if i == j
).
Consider what happens in the two lots of code if i
is zero.
In the first lot of code, the inner loop always iterates five times, and output is produced for all the values of j != i
. For i
equal to zero, this means four lines of output are produced (for j
with each of values 1
, 2
, 3
, 4
but not for 0
).
In the second lot of code, with i
equal to zero, i != j
will be false on the first value of j
(zero) so the inner loop body will never be executed - and the loop body will not be executed for subsequent values of j
. No output will be produced.