The Documentation for While says:

Unless an explicit Return is used, the value returned by While is Null.

But how do I implement it? I'd like to build a function f[..., k_:0]:= While[test(k), k++; ...] that tests a condition against increasing values of k starting from zero and eventually returns the value that makes test(k) return False (or True).

  • 1
    $\begingroup$ k in your function is going to be a number (zero by default), not a variable, and so the statement k++ cannot be evaluated and will throw an error. $\endgroup$
    – Roman
    Mar 22 at 18:23

Here is an example. The condition is that k be at least equal to a+b. Since we cannot increment k we set the variable t to the value of k. The While increments t until it is equal or greater than a+b. At this point, just using t by itself will return the value of t.

f[a_, b_, k_ : 0] := 
  Block[ {t},
   t = k;
    While[t < a + b, t++];

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy