Search code examples
delphidelphi-7

While loop vs Repeat loop delphi


Was looking on Google if there was a major difference betweeen while and repeat..until loops, I didn't find anything useful or what I was looking for.

I noticed that the while loop makes my programs unresponsive, and the repeat works better than while. Is there any specific reason for this, or should one use one another in different scenarios?

Here's my code in a while loop:

var
  m,val : Integer;
  i,k   : Real;
begin
  val := StrToInt(edtShot.Text);
  i := sqr(k);
  k := sqrt(i+val);
  m := 0;

    while i <= 0 and k <= 10 do
      begin
        inc(m);
      end;
end;

and here it is with a repeat loop:

var
  m,val : Integer;
  i,k   : Real;
begin
  val := StrToInt(edtShot.Text);
  i := sqr(k);
  k := sqrt(i+val);
  m := 0;
    repeat
      inc(m);
    until i > 0 and k > 10;
end;

BTW I know the code above doesn't really make much sense, just an example.


Solution

  • A 'repeat' loop is guaranteed to execute at least once as the terminating condition is checked only after the loop has executed once. A 'while' loop may not even execute once as the condition is checked before the loop is executed.

    Other than that, they should take exactly the same amount of time to execute.