2

I'm a Mathematica beginner.

I want to define a factorial function in a procedural way. There are other ways to define factorial function, but I'm asking about the Mathematica grammar equivalent to a for-loop in C++.

Here is the code in C++. How would I convert the code to Mathematica code?

int fac(int n)
{
    int res = 1;
    for(int i=1; i<=n; i++)
    {
        res *= i;
    }
    return res;
}

How do I convert res *= i; and return res; to Mathematica equivalent?

m_goldberg
  • 107,779
  • 16
  • 103
  • 257
jawlang
  • 123
  • 3

1 Answers1

1

Mathematica has a much sneered at For function that exists for the purpose of making it easy to translate C/C++ code like yours into Mathematica form. For your function, the translation looks like

fac[n_Integer /; n > 0] :=
  Module[{res = 1, i},
    For[i = 1, i <= n, i++, res *= i];
    res]

and

fac[6]

720

Be aware, however, there is a lot syntactic sugar in this code. In Mathematica, comma ( , ) is the only delimiter. Semi-colon ( ; ) is neither a delimiter nor a terminator -- it is the binary operator form of the function CompoundExpression. Return is essentially never needed. Mathematica functions return the value of the last expression they evaluate. Module is a form that localizes variables, but not quite in the same way the { ... } does in C++.

m_goldberg
  • 107,779
  • 16
  • 103
  • 257