Re: Difference between ; and , in for loop
- To: mathgroup at smc.vnet.net
- Subject: [mg113957] Re: Difference between ; and , in for loop
- From: Bill Rowe <readnews at sbcglobal.net>
- Date: Fri, 19 Nov 2010 05:09:40 -0500 (EST)
On 11/18/10 at 7:03 AM, graser at gmail.com (graser) wrote: >Would anyone explain me the difference between ; and , in >conditional loop like for loop? For example, >1) For[i = 1, i < 2, i++; Print[i]] Answer is 2 >But >2) For[i = 1, i < 2, i++, Print[i]] The Answer is 1 >Why does first loop get 2 instead of 1? In Mathematica a semicolon is used to form a compound expression. And Mathematica returns the result of the last part of any compound expression encountered. So, when writing For[i = 1, i < 2, i++; Print[i]] the increment portion is the compound expression i++;Print[i] and the body of the loop is Null since nothing is given. So, the loop executes once then increments i to 2 and prints i. Now when you write For[i = 1, i < 2, i++, Print[i]] the body of the loop is the Print[i] portion. So, i is set to 1. The Print[i] prints a 1. Then I is incremented to 2 and the loop ends In both cases the For loop works exactly the same. That is the body is i is initialized to 1, the body is executed, the loop variable is incremented then checked to see if the loop should end.