# For loops in Mathematica [duplicate]

I'm actually the first time using loops in Mathematica. For example, I have:

For[i = 1, i <= n, i++,
For[j = 1, j <= n, j++, ....]


How it is possible now to loop only over i≠j ?

Best regards

• n = 5; For[i = 1, i <= n, i++, For[j = 1, j <= n, j++, If[i != j , Print["i=", i, " j=", j] ] ] ] screen shot to confirm the result !Mathematica graphics – Nasser Nov 16 '14 at 18:56
• Do[If[i != j, ...], {i, n}, {j, n}]. If you're a beginner, try to avoid For in favour of functional constructs and Do. – Szabolcs Nov 16 '14 at 18:59
• Do[..., {i, n}, {j, Drop[Range[n], {i}]}] is an alternative. – Michael E2 Nov 16 '14 at 20:58
• To close-voters: It seems to me that the answer to the main question of how to skip i == j is not easily deduced from the cited duplicate. It may not be a very deep question but it does have at least one efficient solution peculiar to Mathematica (and perhaps others) that is not the standard Fortran/C/Java solution. – Michael E2 Nov 17 '14 at 13:39

In Mathematica you can iterate over i != j with

Do[<code>, {i, n}, {j, Drop[Range[n], {i}]}]


In a sense it really does the actual iteration desired. The following iterates over all pairs {i, j}, although <code> is executed only for i != j.

Do[If[i != j, <code>], {i, n}, {j, n}]


The difference in speed is minimal but measurable:

With[{n = 2000},
Do[1, {i, n}, {j, Drop[Range[n], {i}]}]
] // AbsoluteTiming
(*  {0.216874, Null}  *)

With[{n = 2000},
Do[If[i != j, 1], {i, n}, {j, n}]
] // AbsoluteTiming
(*  {2.202791, Null}  *)


It may seem like a lot, but the execute time of <code> is likely to be an order of magnitude larger at least.

To save a couple of milliseconds over the first loop, there's this:

With[{n = 2000},
With[{r = Range[n]},
Do[1, {i, n}, {j, Drop[r, {i}]}]
]] // AbsoluteTiming
(*  {0.210090, Null}  *)


A very small, but seemingly persistent advantage, even with GeneralUtilitiesAccurateTiming`.