# Want explanation of when different looping constructs are appropriate [duplicate]

For example when would you use a Do loop over a For loop? For which tasks would you use Map, Table, Scan, et cetera? I'm quite new to Mathematica and I don't really get what the advantages of any of these loops are over the standard For loop whose use seems to be so harshly discouraged here on StackExchange.

• Regarding Do vs For: if you can use Do, do not use For. For is less readable and introduces global variables which you'd have to localize manually. For is not generally standard, it is just a convenient construct in some procedural languages. If you compare code using For with code equivalent using Do, it should be clear why Do is usually much more convenient in Mathematica. – Szabolcs Jan 2 '14 at 18:49
• Regarding functional vs procedural (Table/Map vs Do), the functional approach typically gives better performance and more concise and readable code in Mathematica. You'll of course need to get used to thinking in terms of these constructs first, and if you're used to writing C code, using these will not come naturally right away. – Szabolcs Jan 2 '14 at 18:51
• But in any case - use whatever makes you happy. Once performance becomes important, you´ll notice the differences. Otherwise your question is rather broad... – Yves Klett Jan 2 '14 at 18:55
• Do can directly loop over the elements of a list, For can't. Compare Do[Print[i],{i,myList}] vs For[i=1,i<Length[myList],i++,Print[myList[[i]]]]. Of course, Map (/@) is shorter: Print/@myList. – Sjoerd C. de Vries Jan 2 '14 at 18:56
• In the particular case of For, I think it's our collective experience that you very very rarely need to go "so general"; almost always there's a better alternative. – Rojo Jan 2 '14 at 19:02