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?
7
$\begingroup$
$\endgroup$
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
.
i=0
, usei++
in each iteration and add a condtion e.g.And[test, i < 100]
? $\endgroup$ – Kuba♦ Jun 3 '14 at 12:28i
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, initializei
with a negative number. But this is really a matter of taste; counting down traditionally was done because of theJCXZ
x86 instruction. It's obviously not really relevant to Mathematica, being an interpreted language. $\endgroup$ – Oleksandr R. Jun 3 '14 at 12:37