# how to achieve “for(int i,i<=3,i++){}” of C++ in Mathematica [closed]

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.

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!

• The For command was designed just for this purpose. Commented Apr 16, 2023 at 3:53
• You can use 'Do' loop. Mathematica automatically localizes the loop variable. Do loop is better than using For loop. Commented Apr 16, 2023 at 3:54
• It is recommend to ignore For in Mathematica. Commented Apr 16, 2023 at 4:20
• I'm a bit confused. How is "i always need to pay attention to variables-namings" related to for loop? Commented Apr 16, 2023 at 4:33
• 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]; ]
– Syed
Commented Apr 16, 2023 at 4:39

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.