# How do I limit the iterations in a while loop?

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?

• start with i=0, use i++ in each iteration and add a condtion e.g.And[test, i < 100]?
– Kuba
Commented Jun 3, 2014 at 12:28
• 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. Commented Jun 3, 2014 at 12:37
• Does the body of your loop run at least once? You could use Do[] instead of While[]. Commented May 25, 2017 at 2:49

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.