Services & Resources / Wolfram Forums
-----
 /
MathGroup Archive
2006
*January
*February
*March
*April
*May
*June
*July
*August
*September
*October
*November
*December
*Archive Index
*Ask about this page
*Print this page
*Give us feedback
*Sign up for the Wolfram Insider

MathGroup Archive 2006

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

Search the Archive

Re: Strange problem with "for" and "while"

  • To: mathgroup at smc.vnet.net
  • Subject: [mg68404] Re: [mg68359] Strange problem with "for" and "while"
  • From: Igor Antonio <igora at wolf-ram.com>
  • Date: Thu, 3 Aug 2006 06:07:39 -0400 (EDT)
  • Organization: Wolfram Research, Inc.
  • References: <200608020924.FAA28590@smc.vnet.net>
  • Reply-to: igora at wolf-ram.com
  • Sender: owner-wri-mathgroup at wolfram.com

LordBeotian wrote:
> When I try to compute this:

This:

> For[k = 1, k < 10, k++,
>     i := 0;
>     While [k > 1, i++; k--];
>     Print[i, k]]
> 

and this:

> 
> k := ...;
> i = 0;
> While [k > 1, i++; k--];
> Print[i, k]
> 

are not the same thing.  Mathematica is doing exactly what you have 
written. :-)  Here are the things that are wrong with your code in the 
first one:

The first time your code runs, the While's body is not evaluated because 
its condition isn't true, as k = 1.  That's fine.  However, after that...

- you set i:=0 every time the For loop starts.  It gets incremented to 1 
inside the While loop, printed, then set back to zero the next time For 
runs.  Thus, your never-ending "1"'s for i.

- The While loop modifies the value of k every time it runs (except the 
first time For's body evaluates).  So k gets incremented by the For 
loop, only to be decremented by the While loop.  Thus, the infinite loop.

Simply insert some print statements and you will understand what's going 
on.  Also, it may be hard to abort the evaluation, but you can quit the 
kernel to stop it promptly.

aIn[1]:=
For[k=1,k<10,k++,
   i:=0;
   Print["i: ",i];
   Print["k: ",k];
   While[k>1,Print["here."];i++;k--];
   Print[i,k]
   ]
 From In[1]:=
i:  0
 From In[1]:=
k:  1
 From In[1]:=
0 1
 From In[1]:=
i:  0
 From In[1]:=
k:  2
 From In[1]:=
here.
 From In[1]:=
1 1
 From In[1]:=
i:  0
 From In[1]:=
k:  2
 From In[1]:=
here.
 From In[1]:=
1 1
-- 

--
Igor C. Antonio
Wolfram Research, Inc.
http://www.wolfram.com

To email me personally, remove the dash.


  • Prev by Date: RE: find area bounded by three linear functions
  • Next by Date: Pattern match question
  • Previous by thread: Strange problem with "for" and "while"
  • Next by thread: Re: Strange problem with "for" and "while"