1

Why does Print[n] produce output inside a For loop, while Sqrt[n] (as well as many other functions) does not?

enter image description here

In addition can you get Print[n] to single space its output?

m_goldberg
  • 107,779
  • 16
  • 103
  • 257
  • 4
    For[start,test,incr,body] evaluates body, but "Unless an explicit Return is used, the value returned by For is Null." – kglr Sep 20 '18 at 19:18
  • 3
    Well, as a C programmer what output would you expect if you run for (i=0; i < 5; i++) { sqrt(i); }? It's exactly the same thing. printf prints to the screen and sqrt doesn't. Furthermore, for in C is not an expression so it doesn't have a value (even if the sqrt inside does). In Mathematica everything is an expression, but where it doesn't make sense to return a value, Null is returned. – Szabolcs Sep 20 '18 at 19:18
  • "In addition can you get Print[n] to single space its output?" Each Print will create a separate cell in the notebook. Thus this is not about single or double-spacing but about the top and bottom margins of a "Print" style cell. This is defined by the stylesheet and can be changed. In command line mode, each Print outputs on a new line (with no empty lines inbetween). – Szabolcs Sep 20 '18 at 19:32
  • If you have a C background, you might be interested in this. (This is not a direct comment on this question. It is entirely reasonable to want to understand how For works, but after that, it's probably better if you don't use it.) – Szabolcs Sep 20 '18 at 19:37
  • To answer the 2nd part of your question about spacing, to get any kind formatting from Print you must wrap the expression you want to print with one Mathematica many formatting functions. Since you new to Mathematica, I suggest you look at Row and Column for spacing control. Basic vertical spacing: Print[Column[{a, b, c}, Spacings -> 0]]. Basic horizontal spacing: Print[Row[{a, b, c}, " "]]. – m_goldberg Sep 21 '18 at 03:55
  • @Szaboics Of course C requires a printf inside a for loop to get any output, but because entering Sqrt[n] into the Mathematica frontend by itself produces output, I though that putting Sqrt[n] inside a for loop would produce output for each iteration, the same as unrolling the loop by hand. Fortunately, however using Print[Sqrt[n]] inside the for loop does work, as in For[n = 0, n < 5, n++, Print[Sqrt[n]]]. By the way, thanks for the link explaining more about For[] and Do[]. – hagbard7000 Sep 21 '18 at 17:42

2 Answers2

3

Because Print puts text on your screen as a side effect. The result of a For loop, however, is Null.

Mathematica is an expression rewriting language, very different from C. Using C programming style is inadvisable, especially because it will confuse you as a C programmer.

I suggest:

Table[Sqrt[n], {n,1,5}]
John Doty
  • 13,712
  • 1
  • 22
  • 42
1

Another method, sticking with For

Reap[For[i = 0, i < 4, i++, Sow[Sqrt[i]]]][[2, 1]]

{0, 1, Sqrt[2], Sqrt[3]}

NonDairyNeutrino
  • 7,810
  • 1
  • 14
  • 29