# How to put Break command within a Do loop over 2 variables

Suppose I have the code

Do[If[f[i,j]==1,{output[i]=j,Break},Continue],{i,1,5},{j,1,1000}]


Where $$f$$ is just a function.

I want the code to find the first $$j$$ that works for $$i$$, then Break and then find the first $$j$$ that works for the next $$i$$, until a $$j$$ has been found for each $$i$$.

Instead what is happening is the code seems to go through all the $$j$$’s for each $$i$$ and then it remembers the last $$j$$ that works as output[i].

First of all, the correct commands are Break[] and Continue[], you are missing the square brackets.

Secondly, you do not need Continue[].

Thirdly, use ; instead of , to join two expressions.

Lastly, Break[] exits the nearest enclosing Do, so use two separate Do statements:

Do[Do[If[f[i, j] == 1, output[i] = j; Break[]], {j, 1, 1000}], {i, 1, 5}]


More Mathematica-like would be on-demand calculation and memoization:

Clear[output];
output[i_] := output[i] = SelectFirst[Range, f[i, #] == 1 &]


Alternatively, you can try

Clear[output];
output[i_] := output[i] =
j /. FindInstance[f[i, j] == 1, j, PositiveIntegers, 1][]


which may use better tools than simply iterating over $$j$$.