5
$\begingroup$

Is there a way to limit the number of iterations in a while loop? Right now I am cleaning up the code, and for now if I make a mistake, the loop keeps going forever. I'd like to be able to limit the number of times it will run through while I am working on it. Is that possible?

$\endgroup$
  • 3
    $\begingroup$ start with i=0, use i++ in each iteration and add a condtion e.g.And[test, i < 100]? $\endgroup$ – Kuba Jun 3 '14 at 12:28
  • 1
    $\begingroup$ The way I'd do it is to initialize i with the number of iterations you want to define as your maximum, and have it count down: And[test, i-- == 0]. Then if you want to have infinite iterations later, initialize i with a negative number. But this is really a matter of taste; counting down traditionally was done because of the JCXZ x86 instruction. It's obviously not really relevant to Mathematica, being an interpreted language. $\endgroup$ – Oleksandr R. Jun 3 '14 at 12:37
  • $\begingroup$ Does the body of your loop run at least once? You could use Do[] instead of While[]. $\endgroup$ – Matthew Heaney May 25 '17 at 2:49
7
$\begingroup$

As an alternative to a manual check of the iterator, as proposed by Kuba, you could refactor to use NestWhile by converting your body and test to functions without parameters:

n = 1; NestWhile[(Print[n]; n++) &, , (n > 0) &, 1, 7];

The test n > 0 would normally result in an infinite loop, but here it is limited to 7.

$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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