# How to use If and Goto in Table loop? [closed]

I have the following code,

j=0;
Table[{Label[1], j = j + 1, i, If[j == 2, Goto[1], Continue]}, {i, 1,10}]

which does not work; I get does not find Label[1] and for other initial values of j, I get the following result:

{Label[1], 3, 1, Continue}, {Label[1], 4, 2, Continue}, {Label[1], 5, 3, Continue}, {Label[1], 6, 4, Continue}, {Label[1], 7, 5, Continue}, {Label[1], 8, 6, Continue}, {Label[1], 9, 7, Continue}, {Label[1], 10, 8, Continue}, {Label[1], 11, 9, Continue}, {Label[1], 12, 10, Continue}}

What I intended to do was: when j is equal to 2, the i in loop does not change until j gets added by one and then it continues. Could you please help me where I made mistake? Thanks

• Can you please explain what output you expect to see? There is probably a much simpler way to accomplish the task. – bill s Aug 30 '18 at 3:09

Maybe this does what you want?

j = 0;
Table[Label[1]; j = j + 1; i; If[j == 2, Goto[1]]; j, {i, 1, 10}]

{1, 3, 4, 5, 6, 7, 8, 9, 10, 11}

The main problems where the commas; they have to be semicoli. Notice also that the braces { and } in Mathematica are used as delimiters for lists and not for code blocks -- contrary to C. For code blocks, just use parentheses ( and ).

Continue is not really necessary here. If you insist on using it, please use Continue[] instead (notice the brackets).

• thank you, but what I wanted, was when j=2 goes back without changing i, in this case when j=2, it goes back without changing i could you please advise me in this respect> – kmsin Aug 30 '18 at 11:44
• @kmsin I don't understand your question. When j equals 2, the proposed algorithm does jump back to Label[1] without changing i. – Henrik Schumacher Aug 30 '18 at 11:47
• Ah, yes. Thank you so much Herik, I really appreciate it. – kmsin Aug 30 '18 at 11:52
• You're welcome. – Henrik Schumacher Aug 30 '18 at 11:53
• could you please tell me what the problem is with this one? pos = Table[ Label[2]; {x[i] = 20*RandomReal[], y[i] = 20*RandomReal[]}, Table [If[Sqrt [(x[i] - x[j])^2 + (y[i] - y[j])^2] < 4, Goto[2] ], {j, 1, i - 1}], {i, 1, 10}] – kmsin Aug 30 '18 at 19:04

There are easier ways to "skip a beat". For example:

Table[If[i == 2, Nothing, i], {i, 1, 11}]

If already does what you want:

j = 0;
Table[j++; If[j == 2, j++; j, j], {i, 1, 10}]

A different way of doing this might be:

Complement[Table[j, {j, 1, 11}], {2}]
• You can format inline code and code blocks by selecting the code and clicking the {} button above the edit window. The edit window help button ? is useful for learning how to format your questions and answers. You may also find this meta Q&A helpful – Michael E2 Aug 30 '18 at 16:13