1
$\begingroup$

when i use Mathematica to do some small programmings, i always need to pay attention to variables-namings, i just wonder is there a way to achieve “for(int i,i<=3,i++){}” of C++ in Mathematica.

After some answers:

i'm sorry i have not state the question clearly, before your answers, i knew the For[] function, what i want emphasis is variable-localization. and after my test, variables in For[] will exist after For[], but Do[] does have a good variables-localizations, thanks Nasser. In a word, let's use Do[] function!

$\endgroup$
6
  • $\begingroup$ The For command was designed just for this purpose. $\endgroup$
    – Eric Brown
    Commented Apr 16, 2023 at 3:53
  • 3
    $\begingroup$ You can use 'Do' loop. Mathematica automatically localizes the loop variable. Do loop is better than using For loop. $\endgroup$
    – Nasser
    Commented Apr 16, 2023 at 3:54
  • 3
    $\begingroup$ It is recommend to ignore For in Mathematica. $\endgroup$
    – cvgmt
    Commented Apr 16, 2023 at 4:20
  • $\begingroup$ I'm a bit confused. How is "i always need to pay attention to variables-namings" related to for loop? $\endgroup$
    – xzczd
    Commented Apr 16, 2023 at 4:33
  • 1
    $\begingroup$ If you have started learning Mathematica, then you will find that the introductory book written by the inventor is a good learning resource. There is a fast intro for math students as well as a fast intro for programmers to choose from. For now: For[i = 1, i <= 3, i++, Echo[i]; ] $\endgroup$
    – Syed
    Commented Apr 16, 2023 at 4:39

1 Answer 1

6
$\begingroup$

When we write for(int i=0,i<=3,i++){} in C++, as opposed to int i; for(i=0,i<=3,i++){}, the variable name i is declared to be an int in the scope of the {}.

In Mathematica, we say that such a variable is localized. For example, in the Details section of the documentation for Table we read that "Table effectively uses Block to localize values or variables." This means Mathematica always localizes the index of the Table command.

Unlike Table, the variable name of the index of the For command (in Mathematica) is not localized. We could localize the variable name by wrapping the For in a Block. For example, Block[{i},For[i=0,i<=3,++i, Echo@i]]. However, it would be better to use the Do command or Table or any of some other Looping Constructs

The Details section of the documentation for Do also says "Do effectively uses Block to localize values or variables." This would be the preferred way to localize the index.

$\endgroup$
1
  • $\begingroup$ thanks, your answer clearly explained the principle and mechanism of localization of Table[] Do[]. $\endgroup$ Commented Apr 16, 2023 at 10:14

Not the answer you're looking for? Browse other questions tagged or ask your own question.