PDA

View Full Version : While loop question



Traveler
19-02-2003, 05:11 PM
Ok, after a hard days work, I'm not seeing things as clear I would like to so I'm hoping you folks could help me here...

I was expecting to see these loops doing exactly the same, but they don't... why?
procedure TForm1.Button1Click(Sender: TObject);
var x, y: integer;
begin
x := 0;
y := 0;
while x < 3 do
begin
inc(x);
while y < 3 do
begin
inc(y);
showmessage('A:'+inttostr(x)+','+inttostr(y));
end;
end;

for x := 1 to 3 do
begin
for y := 1 to 3 do
begin
showmessage('B:'+inttostr(x)+','+inttostr(y));
end;
end;
end;

Also, as you are probably wondering why I wanted to know: here's my next question. Is a while loop in this particular case faster? (Provided that they give the same outcome)

MarkyD
19-02-2003, 05:46 PM
In the while-loops, y isn't being initialized to 0 before each inner-loop. If you change it so y is initialized to 0 within the outer-loop instead of before it, the while-loops and for-loops should both do the same thing.

procedure TForm1.Button1Click(Sender: TObject);
var x, y: integer;
begin
x := 0;
while x < 3 do
begin
inc(x);
y := 0;
while y < 3 do
begin
inc(y);
showmessage('A:'+inttostr(x)+','+inttostr(y));
end;
end;

for x := 1 to 3 do
begin
for y := 1 to 3 do
begin
showmessage('B:'+inttostr(x)+','+inttostr(y));
end;
end;
end;


Also, as you are probably wondering why I wanted to know: here's my next question. Is a while loop in this particular case faster? (Provided that they give the same outcome)
No idea.

Alimonster
19-02-2003, 05:47 PM
The while loop behaves differently because you've not set the y var to 0 in the *inner* loop. It'll run through one iteration of the x loop, doing 3 iterations of the y loop (with three messages). The next time through, y will not be < 3 so the inner loop won't execute again.

Answer to the second question: maybe the while will be faster, maybe not, but the difference probably won't be significant. It's exceptionally unlikely to ever be a bottleneck. Consider the following code snippet to put things into perspective:

for i := 1 to 3 do
begin
CalculatePiToFiveBillionDecimalPoints;
end;

Now, do you think you'd get more mileage out of changing from a for loop to a while loop, or optimising somewhere else? ;)

If in doubt, write a small test program and compare the assembly, or do a timed test.

The above isn't an exact answer to your question: this is, though (http://www.optimalcode.com/general.htm#forwhile) :)

Traveler
20-02-2003, 08:54 AM
Thank you, MarkyD and Alimonster for the replies.
The solution is sooo simple, can't believe I didn't saw that one :oops:

The site you provided, Alimonster, explained it pretty well...
Although you also made me realize that there are more ways to increase speed than changing the for-loop, into a while-loop.