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?
TimesByfunction has exactly the same syntax as C; and you do not need theReturnfunction in this case, simply put the return value at the end of the function without semicolon. – vapor Mar 07 '17 at 06:06TimesBy, When must I use the Return function?, Alternatives to procedural loops and iterating over lists in Mathematica. One solution:Module[{res = 1}, Do[res *= i, {i, #}]; res] &. More idiomaticallyProduct[i, {i, #}] &– Mr.Wizard Mar 07 '17 at 08:42