[Date Index] [Thread Index] [Author Index]
Re: Strange problem with "for" and "while"
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:= 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:= i: 0 From In:= k: 1 From In:= 0 1 From In:= i: 0 From In:= k: 2 From In:= here. From In:= 1 1 From In:= i: 0 From In:= k: 2 From In:= here. From In:= 1 1 -- -- Igor C. Antonio Wolfram Research, Inc. http://www.wolfram.com To email me personally, remove the dash.