Re: For Loop and Array related

*To*: mathgroup at smc.vnet.net*Subject*: [mg58018] Re: [mg57971] For Loop and Array related*From*: yehuda ben-shimol <bsyehuda at gmail.com>*Date*: Thu, 16 Jun 2005 05:36:57 -0400 (EDT)*References*: <200506150958.FAA29716@smc.vnet.net>*Reply-to*: yehuda ben-shimol <bsyehuda at gmail.com>*Sender*: owner-wri-mathgroup at wolfram.com

The format of the For[] function is For[Init, condition, increment, body]; You have a problem at the part of the condition. I'm sure you ment For[i = 1, i <= 16000, i++, Lattice[[Random[Integer, {1, 100}]]]++] Otherwise i will be set to 16000 and the loop wil not be executed yehuda p.s. it is better to use the Do loop in this case, that is Lattice= Table[0, {n, 100}]; Do[Lattice[[Random[Integer, {1, 100}]]]++, {16000}]. This way you probably will avoide some of these errors in the future yehuda On 6/15/05, mchangun at gmail.com <mchangun at gmail.com> wrote: > Hi All, > > I have an array with 100 elements, all set to zero initially. Then I > want to randomly choose one element and increase its value by one, and > repeat this 16000 times. Here is my code: > > Lattice = Table[0, {n, 100}]; > For[i = 1, i = 16000, i++, Lattice[[Random[Integer, {1, 100}]]]++] > > So now if I add all the elements in the list Lattice together, I should > get 16000 (I use Total[Lattice] to get the sum of the list). But this > doesn't happen, and strangely, each time I run this, the sum of the > list is different! What am I doing wrong? > > Also I'm aware that a lot of Mathematica newbies try and write code > like it were C++ and I think i've fallen into this trap as well. So is > there a different (more Mathematica) way which I can implement the > above? > > Thanks in advanced. > >

**References**:**For Loop and Array related***From:*"mchangun@gmail.com" <mchangun@gmail.com>