# How can I do a Do While loop [duplicate]

Many languages have a Do While loop, how can I do one in Mathematica ?

• Reminds me... Nov 14, 2015 at 13:12
• @J.M. Mr. Wizard deleted it... mathematica.stackexchange.com/q/44224/5478
– Kuba
Nov 14, 2015 at 13:15
• @Kuba, hmm, I'd vote to undelete if my powers weren't unilateral. Why not cast an undelete vote, and hope others do so as well? (That will have the unfortunate effect of making this a dupe, tho.) Nov 14, 2015 at 13:24
• @J.M. can't vote to undelete, it was deleted by moderator.
– Kuba
Nov 14, 2015 at 13:26
• Alright I set this one as a dupe. If anyone thinks the other thread should be reopened, cast your vote. Nov 14, 2015 at 13:29

This can be done much easier by putting the body of the loop into the test, like so:

While[body;test]


For example:

While[False,Print["Evaluated body"]]


gives no output, whereas

While[Print["Evaluated body"];False]
(* Evaluated body *)


does.

PS: The documentation for While presents my approach as the first example under "Scope" and @faysou's approach under "Generalizations and extensions".

• Nice, I didn't know this approach. I wrote another function as it makes it easier for me to explicitely see a DoWhile as an abstraction of a concept, plus I think it's a neat and simple illustration of metaprogramming. Nov 14, 2015 at 13:10

Using some basic meta programming it's possible to do it.

SetAttributes[DoWhile,HoldAll];
DoWhile[expr_,condition_]:=
While[True,
expr;

If[! condition,
Break[];
];
];


For example

i=0
DoWhile[i++,i<0] (*i=1*)

i=-2
DoWhile[i++,i<0] (*i=0*)