Breaking a While loop

A simple example to illustrate what I'm talking about:

m=0;
While[m<=50,
m=m+1;
p=m]


The result is:

m=51
p=51


In languages like Fortran or VB, the loop would stop exactly when m=51 and wouldn't do "p=m". The result would be:

m=51
p=50


How to program Mathematica to stop exactly when the condition is met?

• While[ (m=m+1)<=50 , p=m]. No way Fortran auto exits a loop as you claim, by the way. ( I doubt VB does either.. ) – george2079 Jan 13 '15 at 20:56
• You seem to be confusing the test condition with the body that is just one CompoundExpression that will always return m=p. – Yves Klett Jan 13 '15 at 20:58

You may be thinking of another idiom.

http://en.wikipedia.org/wiki/Do_while_loop#Equivalent_constructs

m = 0;
While[True, m = m + 1;
If[Not[m <= 50], Break[]];
p = m]


I suspect you are seeking a For loop:

For[m = 0, m <= 50, ++m, p = m]

{m, p}

{51, 50}


However as george2079 already showed you could also use While:

m = 0;
While[(++m) <= 50, p = m]

{m, p}

{51, 50}


Use

 m=0;
While[m<=50,p=m;
m=m+1
]


Reversing the order of the last 2 instructions fixes the problem.

• another valid approach. don't know why the downvote.. – george2079 Jan 14 '15 at 13:05