3
$\begingroup$
f[n_] := (
  While[n < 10,
    n = n + 1];
  n
)

I am trying to learn mathematica on my own. I am trying to write a function that contains a while loop, but I can't get anywhere. When I key in f[3] I don't get 10, instead I get 3. Can anyone please help?

$\endgroup$
  • 3
    $\begingroup$ If you are not familiar with Mathematica and functional programming, and you want to learn it on your own, I suggest you to do some reading first. Mathematica Stackexchange is surely a good place to look at, but I will pair it with reading a book or something. There are many out there, for example: mathprogramming-intro.org $\endgroup$ – Fraccalo Jan 23 at 12:27
  • 2
    $\begingroup$ I'm telling you this because Mathematica programming paradigm (or better, the arguably best/most used way of programming in mathematica) is quite different from other programming language that you might already know, hence it's good (if not necessary) to have some background reading first. For example, you won't find many mathematica codes that use while loops ;P $\endgroup$ – Fraccalo Jan 23 at 12:29
7
$\begingroup$

In addition to the very good suggestions by Fraccalo, the issue here is that Mathematica refuses to overwrite arguments of functions (in general). So you have to introduce a local variable like this:

f[n0_] := Module[{n = n0},
  While[n < 10, n = n + 1];
  n
  ]

There is a way to emulate so-called call-by-reference that you might know from C-like programming languages. This can be done as follows; however, I would strongly recommend to ignore this feature until you are more proficient with the language, because this is not the way one should program in Mathematica:

SetAttributes[g,HoldAll];
g[n_]:= While[n < 10, n = n + 1];

Then you can do

n=3;
g[n];
n

10

but g[3] won't work any more (because 3 is not a variable and thus does not have an "adress" to write to).

$\endgroup$

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.