1
$\begingroup$

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?

$\endgroup$
  • 4
    $\begingroup$ 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.. ) $\endgroup$ – george2079 Jan 13 '15 at 20:56
  • $\begingroup$ You seem to be confusing the test condition with the body that is just one CompoundExpression that will always return m=p. $\endgroup$ – Yves Klett Jan 13 '15 at 20:58
2
$\begingroup$

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]
$\endgroup$
0
$\begingroup$

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}
$\endgroup$
0
$\begingroup$

Use

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

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

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

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.