1

I have a simple function:

f[x0_,y0_]:= Module[{x=x0,y=y0},For[i=0,i<2,i++;Print[x],Print[x+y]];]

So when I call it:
f[2,3]

I get:

5
2
5
2

Why not:

2
5
2
5

as expected? Also my indentation of - or + don't seem to format?

Öskå
  • 8,587
  • 4
  • 30
  • 49
sebastian c.
  • 1,973
  • 2
  • 18
  • 27
  • Try f[x0_, y0_] := Module[{x = x0, y = y0},For[i = 0, i < 2,i++;Print[x]; Print[x + y]];]. This works as you expect it to work. – Öskå Nov 24 '12 at 12:08
  • Hi @Öskå Thanks, but is the semicolon not the standard way of suppressing an output, anyway it works but I can't figure out why comma reverses the order and semicolon works? – sebastian c. Nov 24 '12 at 12:16
  • The Print function will print whether you add a ; in the end or not. Although I have no clue why that comma changes the order. – Öskå Nov 24 '12 at 12:25
  • 2
    With the comma the first print is evaluated during incrementation, and not in the body. Hence the reversed order. http://reference.wolfram.com/mathematica/tutorial/SequencesOfOperations.html – ssch Nov 24 '12 at 12:30

1 Answers1

8

For syntax is like this:

For[start,test,incr,body]

Your first Print is part of the incrementation step, due to ; combining it into one expression

For[i = 0, i <= 3, Print["incrementing from ",i]; i++, Print[i]]
(* Result:
0
incrementing from 0
1
incrementing from 1
2
incrementing from 2
3
incrementing from 3
*)

You can put it all in the body like (note position of commas and semicolons):

For[i = 0, i < 2,i++,Print[x]; Print[x + y]]

I recommend you actively try to avoid For loops when coding in Mathematica, see for instance Functional Programming: Quick Start.

And check the other links in this popular answer under the section Basic advices for people new to Mathematica

ssch
  • 16,590
  • 2
  • 53
  • 88