Suppose I have the code


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].


2 Answers 2


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:

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

Alternatively, you can try

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

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


Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.