TransWikia.com

How to get While to Return a Custom Value?

Mathematica Asked by user78013 on July 9, 2021

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).

One Answer

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.

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

Correct answer by Jean-Pierre on July 9, 2021

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP