MathGroup Archive 2011

[Date Index] [Thread Index] [Author Index]

Search the Archive

Re: While Loop

  • To: mathgroup at smc.vnet.net
  • Subject: [mg123612] Re: While Loop
  • From: David Bailey <dave at removedbailey.co.uk>
  • Date: Tue, 13 Dec 2011 05:40:51 -0500 (EST)
  • Delivered-to: l-mathgroup@mail-archive0.wolfram.com
  • References: <jbvjus$j47$1@smc.vnet.net>

On 10/12/2011 12:39, Joao wrote:
> Hi, everybody
>
> Could someone help me regarding the While Loop.
>
> While[test,body]
>
> In the help "While" it is stated that the test may be evaluated at the end of the loop, instead of at the beginning. However in the tutorial on Loops and Control structures it is stated that the While always evaluates the test at the beginning.
>
> I would like to know if it is really possible to evaluate the test inside de While at the end of the loop. This is a feature that would be useful for what I'm doing, however I haven't been able to get it working and I don't know, taking into consideration the above, if I am doing something wrong or if it is really not possible to do.
>
> Thanks in advance
>
> Joao
>
I think you are perhaps referring to this example from the help:

While[True,
  n = Input["enter an integer"];
  If[! IntegerQ[n] || n <= 0, Break[]];
  Print[n, "=", FactorInteger[n]]
  ]

In this case, the "test" is just True - it will always pass - but the 
"real test" is the line:

If[! IntegerQ[n] || n <= 0, Break[]];

This breaks out of the loop if n is not an integer greater than 0.

Thus, in reality, a loop can be structured with exit(s) wherever you like.

BTW, Unlike some Mathematica programmers, I think the While construct is 
extremely useful for handling some looping situations, but it is always 
worthwhile considering if a functional programming construct, such as 
Map, would achieve the same result.

David Bailey
http://www.dbaileyconsultancy.co.uk





  • Prev by Date: Re: NMinimize problem: fct minimized uses FindRoot
  • Next by Date: Re: Inverse Function
  • Previous by thread: Re: While Loop
  • Next by thread: NMinimize problem: fct minimized uses FindRoot